Skip to content

Instantly share code, notes, and snippets.

@j0hj0h
Last active August 5, 2016 14:03
Show Gist options
  • Save j0hj0h/43ffc9d024abdace7de6efb0265c5891 to your computer and use it in GitHub Desktop.
Save j0hj0h/43ffc9d024abdace7de6efb0265c5891 to your computer and use it in GitHub Desktop.
Wordpress: responsive embeds
<?php
/*
Wraps the video embed code so that it takes the full width of the parent element
and resizes keeping it's aspect ratio.
Just tested for Vimeo and YouTube iframes so far ...
*/
add_filter('embed_oembed_html', function($html) {
// preg dimensions from iframe attributes
$width = preg_replace('/.*width="(\d*)".*/', '\\1', $html);
$height = preg_replace('/.*height="(\d*)".*/', '\\1', $html);
// calculate percentage for padding bottom hack
$padding_bottom_percent = ($height / $width * 100);
// add style attribute to iframe tag
$html_with_style = preg_replace('/<iframe/', '<iframe style="position: absolute; left: 0; top: 0; width: 100%; height: 100%;"', $html);
// return wrapped iframe
return '
<div style="position: relative; padding-bottom: ' . $padding_bottom_percent . '%">
' . $html_with_style . '
</div>';
}, 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment