Auto-Populate Image Alt Text, Caption, and Description on Upload in WordPress

How to fill in the image alt automatically after upload

Today we look at an SEO question again. Sites with images, and they are the overwhelming majority, are indexed better when the alt attributes of their images are filled in. They also matter for accessibility. But editors rarely fill in the alt manually.

Problem: Can the alt attribute be filled in automatically when an image is uploaded to the Media Library, or does it have to be done manually?

Solution: Yes, it can. Below is how to do it without a plugin: after the upload, take the file name, turn it into text and write it to the alt, the caption and the description. Add this code to functions.php:

<?php
add_action( 'add_attachment', 'auto_alt_title_caption' );

function auto_alt_title_caption( $attachment_id ) {
    if ( ! wp_attachment_is_image( $attachment_id ) ) {
        return; // skip PDFs, videos and other files
    }

    // WordPress already put the file name without extension into the title
    $text = get_post_field( 'post_title', $attachment_id );
    $text = ucfirst( trim( str_replace( array( '-', '_' ), ' ', $text ) ) );

    // Alt attribute, only if it is empty
    if ( ! get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) {
        update_post_meta( $attachment_id, '_wp_attachment_image_alt', $text );
    }

    // Caption and description
    wp_update_post( array(
        'ID'           => $attachment_id,
        'post_excerpt' => $text, // Caption field
        'post_content' => $text, // Description field
    ) );
}

The file red-sports-car_2020.jpg gets the alt “Red sports car 2020”. If you do not want a caption under every image in the content, remove the post_excerpt line.

Of course, the result is only as good as the file names. IMG_4512.jpg becomes “IMG 4512”, so it is worth asking editors to name the files properly before upload.

NOTE: The function works only for new uploads, not for the images uploaded before. To fill them in, run this code once, for example temporarily in functions.php, open any page and remove it:

<?php
$attachment_ids = get_posts( array(
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'post_status'    => 'inherit',
    'posts_per_page' => -1,
    'fields'         => 'ids',
) );

foreach ( $attachment_ids as $attachment_id ) {
    if ( ! get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) {
        auto_alt_title_caption( $attachment_id );
    }
}

Only images without an alt are changed, so the texts written by hand stay. On a large Media Library this takes time, so run it when the site has few visitors.

Sources:

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