The embed_oembed_html WordPress PHP filter allows you to modify the cached oEmbed HTML before it is displayed.
Usage
add_filter( 'embed_oembed_html', 'your_custom_function', 10, 4 ); function your_custom_function( $cache, $url, $attr, $post_id ) { // Your custom code here return $cache; }
Parameters
- $cache (string|false): The cached HTML result, stored in post meta.
- $url (string): The attempted embed URL.
- $attr (array): An array of shortcode attributes.
- $post_id (int): Post ID.
More information
See WordPress Developer Resources: embed_oembed_html
Examples
Add a custom wrapper to embedded content
Wrap the embedded content with a custom div
element for easier styling.
add_filter( 'embed_oembed_html', 'wrap_oembed_content', 10, 4 ); function wrap_oembed_content( $cache, $url, $attr, $post_id ) { return '<div class="custom-embed-wrapper">' . $cache . '</div>'; }
Change video aspect ratio
Change the aspect ratio of embedded videos to 4:3.
add_filter( 'embed_oembed_html', 'change_video_aspect_ratio', 10, 4 ); function change_video_aspect_ratio( $cache, $url, $attr, $post_id ) { return str_replace( 'width="640" height="360"', 'width="640" height="480"', $cache ); }
Add lazy loading to iframes
Add the loading="lazy"
attribute to iframe elements to enable lazy loading.
add_filter( 'embed_oembed_html', 'add_lazy_loading_to_iframes', 10, 4 ); function add_lazy_loading_to_iframes( $cache, $url, $attr, $post_id ) { return str_replace( '<iframe ', '<iframe loading="lazy" ', $cache ); }
Remove YouTube related videos
Remove related videos from YouTube embeds.
add_filter( 'embed_oembed_html', 'remove_youtube_related_videos', 10, 4 ); function remove_youtube_related_videos( $cache, $url, $attr, $post_id ) { if ( strpos( $url, 'youtube.com' ) !== false ) { return str_replace( '?feature=oembed', '?feature=oembed&rel=0', $cache ); } return $cache; }
Change Vimeo video quality
Set the quality of embedded Vimeo videos to a lower value for faster loading.
add_filter( 'embed_oembed_html', 'change_vimeo_video_quality', 10, 4 ); function change_vimeo_video_quality( $cache, $url, $attr, $post_id ) { if ( strpos( $url, 'vimeo.com' ) !== false ) { return str_replace( ' src=', ' data-src=', $cache ) . '<script>if (typeof Vimeo != "undefined") { Vimeo.setQuality("240p"); }</script>'; } return $cache; }