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
- Open your active theme’s
functions.phpfile or a custom functionality plugin. - Add the code below.
- Save the file.
- Newly displayed images without an
altattribute will automatically use the attachment title.
Benefits
- Automatically fills missing image alt text.
- Improves website accessibility.
- Enhances image SEO.
/**
* 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 );