Turn On Captions by Default in YouTube Embeds
Adds YouTube's captions setting to embedded videos, so subtitles are shown automatically whenever the video has them.
Opens WPIDE on
Code
// Preferred caption language ('' lets YouTube decide).
$wpide_caption_lang = '';
add_filter( 'embed_oembed_html', function ( $html, $url ) use ( $wpide_caption_lang ) {
if ( ! preg_match( '#youtu\.?be#i', $url ) || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $html;
}
$tags = new WP_HTML_Tag_Processor( $html );
if ( $tags->next_tag( 'iframe' ) ) {
$args = array( 'cc_load_policy' => 1 );
if ( $wpide_caption_lang ) {
$args['cc_lang_pref'] = $wpide_caption_lang;
}
$tags->set_attribute( 'src', add_query_arg( $args, (string) $tags->get_attribute( 'src' ) ) );
}
return $tags->get_updated_html();
}, 10, 2 );
Notes
Change $wpide_caption_lang to a language code such as en or fr to prefer that caption language.
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.