How to auto populate alt attributes after image download

Today, we’ll be review question, aimed at improving SEO, again now. Sites, that contain images, and such an overwhelming majority, better index if their alt attributes of images was populated.

Automatic populate alt attributes of images

Problem: It's possible auto populate alt attributes after image download to Media Library or it need do manually?

Solution: Yes, it's possible. Below we'll review how do it without plugin. Let's add next code to functions.php

<?php

add_action( 'add_attachment', 'auto_alt_title_caption' );

function auto_alt_title_caption( $attachment_ID ) {
 
    $filename = $_REQUEST[ 'name' ];
    $withoutExt = preg_replace( '/\\.[^.\\s]{3,4}$/', '', $filename );
    $withoutExt = str_replace( ['-','_'], ' ', $withoutExt ); 
    $my_post = [
        'ID' => $attachment_ID,
        'post_excerpt' => $withoutExt, // Populate Caption field
        'post_content' => $withoutExt, // Populate Description field
    ];
 
    wp_update_post( $my_post );
 
    // Update Alt attribute
    update_post_meta( $attachment_ID, '_wp_attachment_image_alt', $withoutExt );
}

NOTE: Auto populate alt attributes, works just during loading images. It's means, that function doesn't work for all images which downloaded before. For resolve this trouble use next code.

<?php

$args = [
	'posts_per_page' => -1,
	'post_type' => 'attachment',
	'fields' => 'ids',
	'no_found_rows' => true,
];
		
$attachments_IDs = new WP_Query( $args );

foreach ( $attachments_IDs as $attachment_ID ) {
    auto_alt_title_caption( $attachment_ID );
}

This code enough run one time. After check, then this code may be remove.

Sources:

  1. https://faqwp.com/question/avto-title-i-alt-v-kartinkah-wordpress

Leave Comment

Your email address will not be published.