Skip to main content
Login Join
Snippet · PHP

Automatically Add alt Text to Images from Their Attachment Title

Shared by Amit Dholiya · July 29, 2026 · @wp_get_attachment_image_attributes

1 copy
19 views
Back to Snippets

Description

Images without alt text can negatively impact accessibility and SEO. This snippet automatically uses the image attachment title as the alt attribute whenever an uploaded image doesn’t already have one.

Steps

  1. Open your active theme’s functions.php file or a custom functionality plugin.
  2. Add the code below.
  3. Save the file.
  4. Newly displayed images without an alt attribute will automatically use the attachment title.

Benefits

/**
 * Automatically add alt text to images.
 */
function wpfolks_auto_image_alt( $attr, $attachment ) {

    if ( empty( $attr['alt'] ) ) {
        $attr['alt'] = trim( strip_tags( get_the_title( $attachment->ID ) ) );
    }

    return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'wpfolks_auto_image_alt', 10, 2 );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments