There are several filters in WordPress for altering oEmbed data, depending on when you need to modify the results:
- embed_handler_html
Filters the returned embed handler. - embed_oembed_html
Filters the cached oEmbed HTML. - oembed_result
Filters the HTML returned by the oEmbed provider.
Choose the one that best suits your needs, but keep in mind that each filter acts on data at a different stage of the oEmbed process and could have performance implications.
For instance,
embed_handler_html
is called before data is put in the oEmbed / wp_postmeta cache (so only once per external embed) whileembed_oembed_html
is called after retrieving the oEmbed cache (so every time the item is displayed).If you only need to modify the oEmbed data once,
oembed_result
is probably your best candidate.
To answer your question, here’s an example that modifies the Vimeo and YouTube embed parameters returned from the WordPress wp_oembed_get()
function.
The <iframe> HTML markup is first parsed by PHP’s DOMDocument class, then the embed URL is modified using WordPress’ add_query_arg() function:
/**
*
*/
add_filter( 'oembed_result', function ( $html, $url, $args ) {
$doc = new DOMDocument();
$doc->loadHTML( $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$tags = $doc->getElementsByTagName( 'iframe' );
foreach ( $tags as $tag ) {
$iframe_src = $tag->attributes->getNamedItem('src')->value;
if ( false !== strpos( $iframe_src, 'youtube.com' ) ) {
// https://developers.google.com/youtube/player_parameters
$url = add_query_arg( array(
'autohide' => 1,
'autoplay' => 1,
'controls' => 2,
'feature' => null,
'modestbranding' => 1,
'playsinline' => 1,
'rel' => 0,
'showinfo' => 0,
), $iframe_src );
}
if ( false !== strpos( $iframe_src, 'vimeo.com' ) ) {
// https://developer.vimeo.com/player/embedding
$url = add_query_arg( array(
'autoplay' => 1,
'badge' => 0,
'byline' => 0,
'portrait' => 0,
'title' => 0,
), $iframe_src );
}
$tag->setAttribute( 'src', $url );
$html = $doc->saveHTML();
}
return $html;
}, 10, 3 );