Fill Missing Alt Text in Bulk (Run Once)
A one-off task that gives every image without alt text a description based on its title. Run it from the snippet editor whenever you want to catch up.
Opens WPIDE on
Code
// Maximum number of images to update per run.
$wpide_alt_batch = 500;
if ( ! current_user_can( 'upload_files' ) && ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
$wpide_images = get_posts( array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'fields' => 'ids',
'numberposts' => $wpide_alt_batch,
'meta_query' => array(
'relation' => 'OR',
array( 'key' => '_wp_attachment_image_alt', 'compare' => 'NOT EXISTS' ),
array( 'key' => '_wp_attachment_image_alt', 'value' => '' ),
),
) );
$wpide_updated = 0;
foreach ( $wpide_images as $wpide_image_id ) {
$wpide_alt = preg_replace( '/\b(img|dsc|dscn|pxl|image|photo|screenshot)[\s_\-]*\d+\b/i', '', (string) get_post_field( 'post_title', $wpide_image_id ) );
$wpide_alt = trim( preg_replace( '/[\s_\-]+/', ' ', $wpide_alt ) );
if ( '' === $wpide_alt ) {
continue;
}
update_post_meta( $wpide_image_id, '_wp_attachment_image_alt', sanitize_text_field( ucfirst( $wpide_alt ) ) );
$wpide_updated++;
}
echo esc_html( sprintf( 'Alt text added to %1$d of %2$d images without it.', $wpide_updated, count( $wpide_images ) ) );
Notes
Processes up to 500 images per run; run it again for more. Review important images afterwards, as titles are not always good descriptions.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.