Make WordPress default video embeds responsive

Unfortunately WordPress does not add a div around embed codes by default, so this is the first thing we need to do to get it to work.

Add this to your theme’s functions.php:

/*  Add responsive container to embeds
/* ------------------------------------ */	
function alx_embed_html( $html ) {
	return '<div class="video-container">' . $html . '</div>';
}

add_filter( 'embed_oembed_html', 'alx_embed_html', 10, 3 );
add_filter( 'video_embed_html', 'alx_embed_html' ); // Jetpack

And next up, we need to add the CSS that makes it responsive to our style.css:

.video-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; }
.video-container iframe, .video-container object, .video-container embed, .video-container video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

And that’s it! You now make iframe, object, embed and video (html5) elements responsive. The responsive CSS will always show videos in 16:9 aspect ratio, which is HD.

This code will also work with Jetpack embeds.

57 Responses

  1. Alan De Bortolo says:

    Perfect!

  2. Jonathan says:

    YOU ROCK

  3. hasanbajwa says:

    well i use this on my website but this code is not working.?????

  4. Sandro says:

    I’ve updated your code for Bootstrap 4 Alpha 6:
    1. Only videos (Show the Array on strposa) will get the video alignment.
    2. Videos have max-width: 500px in tinyMCE.
    3. Other content will be centered.

    function naughty_embed_html( $html ) {
    $modified_html = ”;
    if ( strposa( $html, [ ‘youtu.be’, ‘youtube’, ‘vimeo’ ] ) ) {
    // If video

    // Remove ‘height=”xyz”‘ and ‘width=”xyz”‘
    $html = preg_replace( ‘/width=”.*?” /’, ”, $html );
    $html = preg_replace( ‘/height=”.*?” /’, ”, $html );

    $modified_html .= ” . $html . ”;
    } else {
    // If something else
    $modified_html .= ” . $html . ”;
    }

    return $modified_html;
    }

    function strposa( $haystack, $needles = [], $offset = 0 ) {
    $chr = [];
    foreach ( $needles as $needle ) {
    $res = strpos( $haystack, $needle, $offset );
    if ( $res !== false ) {
    $chr[ $needle ] = $res;
    }
    }
    if ( empty( $chr ) ) {
    return false;
    }

    return min( $chr );
    }

    And the style:

    .embed-responsive {
    max-width: 500px;
    margin: 0 auto;
    }

    .embed-align-center > *:first-child {
    margin-left: auto !important;
    margin-right: auto !important;
    }

    • Alexander says:

      Thanks for sharing! Can you share the code via pastebin or something similar? The comments section isn’t the best to display code.

  5. alice says:

    thanks, it worked

  6. Thank you ! Works great.

Leave a Reply

Your email address will not be published. Required fields are marked *