Remove Image Tooltips That Repeat the Alt Text
Removes the title attribute from images in your content when it is the same as the alt text, so screen readers do not read the same description twice.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( false === stripos( $content, 'title=' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $content;
}
$tags = new WP_HTML_Tag_Processor( $content );
while ( $tags->next_tag( 'img' ) ) {
$title = trim( (string) $tags->get_attribute( 'title' ) );
if ( '' !== $title && strtolower( $title ) === strtolower( trim( (string) $tags->get_attribute( 'alt' ) ) ) ) {
$tags->remove_attribute( 'title' );
}
}
return $tags->get_updated_html();
}, 20 );
Notes
Titles that add different information are kept.
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.