Use Media Library Alt Text for Images Missing It in Posts
When an image in a post has an empty alt attribute but its Media Library entry has alt text, the library text is used on the page, fixing older posts without editing them.
Opens WPIDE on
Code
add_filter( 'wp_content_img_tag', function ( $image, $context, $attachment_id ) {
if ( ! $attachment_id || ! preg_match( '/\salt=(["\'])\s*\1/', $image ) ) {
return $image;
}
$alt = trim( (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) );
if ( '' === $alt ) {
return $image;
}
return preg_replace( '/\salt=(["\'])\s*\1/', ' alt="' . esc_attr( $alt ) . '"', $image, 1 );
}, 10, 3 );
Notes
Images deliberately left with empty alt text are filled too if the library has a description; clear the library alt text for decorative images.
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.