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.
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:
Saved as a favorite, I really like your blog!
This blog was… how do I say it? Relevant!!
Finally I’ve found something which helped me. Thank you!
You are so interesting! I don’t suppose I’ve truly read something like that before. So great to find someone with genuine thoughts on this issue.
Seriously.. many thanks for starting this up. This web site is something that’s needed on the web, someone with a bit of originality!