Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.