Use the Post Title as Alt Text for Featured Images Without One
When a featured image has no alternative text, outputs the post title as its alt attribute in themes and blocks, instead of leaving it empty.
Opens WPIDE on
Code
add_filter( 'post_thumbnail_html', function ( $html, $post_id ) {
if ( ! $html || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $html;
}
$tags = new WP_HTML_Tag_Processor( $html );
if ( $tags->next_tag( 'img' ) && '' === trim( (string) $tags->get_attribute( 'alt' ) ) ) {
$tags->set_attribute( 'alt', wp_strip_all_tags( get_the_title( $post_id ) ) );
return $tags->get_updated_html();
}
return $html;
}, 10, 2 );
Notes
Only affects images shown as a post's featured image; images that already have alt text keep it.
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.