Make Your WordPress oEmbeds Responsive

If you haven’t experienced the joy of oEmbed in WordPress then it’s a super nice feature. Simply copy and paste a URL from an oEmbed provider in (such as YouTube) and WordPress does the rest.

By default though, WordPress doesn’t embed these responsively, that’s where a small bit of custom code can come in to play.

Important: This is aimed at developers. The following code should go in your child themes functions.php file or in a standalone plugin. Always make a site backup before doing any development work.

The Code

We’re going to use the embed_oembed_html filter to add a container div around the iframe that is eventually output.

if ( ! function_exists( 'my_theme_setup' ) ) {
	function my_theme_setup() {
        add_filter('embed_oembed_html', 'my_responsive_embed', 10, 3);
	}
}
add_action( 'after_setup_theme', 'my_theme_setup' );

function my_responsive_embed($html, $url, $attr) {
    return $html!=='' ? '<div class="embed-container">'.$html.'</div>' : '';
}

So here we’re adding our embed_oembed_html filter after theme setup. The last part of this is to add some CSS to the embed-container we created.

.embed-container { 
    position: relative; 
    padding-bottom: 56.25%; 
    height: 0; 
    overflow: hidden; 
    max-width: 100%; 
} 

.embed-container iframe, .embed-container object, .embed-container embed { 
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
}

Note: This was done with YouTube in mind, but will probably work on most other similar platforms.

Ta-da!

There we have it, if all has gone well then your video embeds will now be full-width and scale down with the screen size of the device.