Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: Add the 'title' attribute to iFrame oEmbeds: https://www.n7studios.co.uk/improving-accessibility-wordpress-oembeds/
<?php
/**
* Adds a title attribute to iframe oembeds
*
* @since 1.0.0
*
* @param string $html HTML
* @param string $url URL to embed
* @param array $attributes HTML Attributes
* @param int $post_id Post ID
* @return string HTML
*/
function add_title_to_iframe_oembed( $html, $url, $attributes, $post_id ) {
// Bail if this isn't an iframe
if ( strpos( $html, '<iframe' ) === false ) {
return $html;
}
// Bail if the attributes already contain a title
if ( array_key_exists( 'title', $attributes ) ) {
return $html;
}
// Define the title for the iframe, depending on the source content
// List is based on supported Video and Audio providers at https://codex.wordpress.org/Embeds
$url = parse_url( $url );
$title = '';
switch ( str_replace( 'www.', '', $url['host'] ) ) {
/**
* Video
*/
case 'animoto.com':
case 'blip.com':
case 'collegehumor.com':
case 'dailymotion.com':
case 'funnyordie.com':
case 'hulu.com':
case 'ted.com':
case 'videopress.com':
case 'vimeo.com':
case 'vine.com':
case 'wordpress.tv':
case 'youtube.com':
$title = __( 'Video Player', 'n7studios' );
break;
/**
* Audio
*/
case 'mixcloud.com':
case 'reverbnation.com':
case 'soundcloud.com':
case 'spotify.com':
$title = __( 'Audio Player', 'n7studios' );
break;
/**
* Handle any other URLs here, via further code
*/
default:
$title = apply_filters( 'add_title_to_iframe_oembed', $title, $url );
break;
}
// Add title to iframe, depending on the oembed provider
$html = str_replace( '></iframe>', ' title="' . $title . '"></iframe>', $html );
// Return
return $html;
}
add_filter( 'embed_oembed_html', 'add_title_to_iframe_oembed', 10, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment