Add Missing Titles to Embedded Iframes
Gives iframes in post content a title attribute when they lack one (for example "YouTube video" or "Embedded map"), so screen reader users know what each frame contains.
Opens WPIDE on
Code
// Host fragment => title used when the iframe has none.
$wpide_iframe_titles = array(
'youtube' => 'YouTube video',
'vimeo' => 'Vimeo video',
'google.com/maps' => 'Embedded map',
'spotify' => 'Spotify player',
'soundcloud' => 'SoundCloud player',
'calendar.google' => 'Embedded calendar',
);
add_filter( 'the_content', function ( $content ) use ( $wpide_iframe_titles ) {
if ( false === stripos( $content, '<iframe' ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $content;
}
$tags = new WP_HTML_Tag_Processor( $content );
while ( $tags->next_tag( 'iframe' ) ) {
if ( '' !== trim( (string) $tags->get_attribute( 'title' ) ) ) {
continue;
}
$src = (string) $tags->get_attribute( 'src' );
$title = 'Embedded content';
foreach ( $wpide_iframe_titles as $needle => $label ) {
if ( false !== stripos( $src, $needle ) ) {
$title = $label;
break;
}
}
$tags->set_attribute( 'title', $title );
}
return $tags->get_updated_html();
}, 20 );
Notes
Add more hosts to the $wpide_iframe_titles list for other services you embed.
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.