Use Image Captions as Alt Text When Alt Is Empty
For image blocks that have a caption but no alternative text, uses the caption text as the alt attribute, so the image is not announced as unlabeled.
Opens WPIDE on
Code
add_filter( 'render_block_core/image', function ( $html ) {
if ( false === stripos( $html, '<figcaption' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $html;
}
if ( ! preg_match( '#<figcaption[^>]*>(.*?)</figcaption>#is', $html, $m ) ) {
return $html;
}
$caption = trim( wp_strip_all_tags( $m[1] ) );
$tags = new WP_HTML_Tag_Processor( $html );
if ( $caption && $tags->next_tag( 'img' ) && '' === trim( (string) $tags->get_attribute( 'alt' ) ) ) {
$tags->set_attribute( 'alt', wp_html_excerpt( $caption, 150, '' ) );
return $tags->get_updated_html();
}
return $html;
} );
Notes
A caption and alt text ideally say different things; treat this as a fallback and write real alt text where you can.
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.