Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wordpress OEmbed for Responsive Video
<?php
/**
* Hook into the oembed to add the correct aspect ratio to your videos added
* with wordpress' oembed feature (i.e. by pasting a URL in the editor)
*/
// TODO: Maybe it should only do this for video sites, and leave everything else alone?
function auginator_oembed_html($html, $url, $attr, $post_id) {
// Parse width and height from the html returned from the oembed call
$width = array();
preg_match( '/width="([^"]*)"/i', $html, $width ) ;
$height = array();
preg_match( '/height="([^"]*)"/i', $html, $height ) ;
// if there is a width and a height attribute,
if ( $height[1] && $width[1] ) {
// calculate ratio for use in the padding-bottom
$ratio = ( $height[1] / $width[1] ) * 100;
// Modify the output HTML with the inline padding-bottom value.
$tag = sprintf('<div class="responsiveEmbed" style="padding-bottom: %s%%">%s</div>', $ratio, $html);
} else {
// just return the oembed html unmodified
$tag = sprintf('<div class="responsiveEmbed">%s</div>', $html);
}
return $tag;
}
add_filter('embed_oembed_html', 'auginator_oembed_html', 99, 4);
// I learned this basic technique from Zurb's wonderful Foundation
// framework years ago – still my favorite for responsive embeds.
.responsiveEmbed {
margin-bottom: 0;
position: relative;
height: 0;
margin-bottom: 1rem;
padding-bottom: 56.25%; //default is 16/9 HD, if we cannot calculate a new one in php, we will use this.
overflow: hidden;
iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment