Skip to content

Instantly share code, notes, and snippets.

@Kevinlearynet
Created April 12, 2012 22:40
Show Gist options
  • Save Kevinlearynet/2371542 to your computer and use it in GitHub Desktop.
Save Kevinlearynet/2371542 to your computer and use it in GitHub Desktop.
This plugin adjusts the WordPress automatic media embeds, allowing for responsive width and height scaling when the device or browser resolution changes.
<?php
/**
* Responsive Embeds in WordPress
*
* Custom embed sizing for basic listing template
*/
class ResponsiveVideoEmbeds
{
/**
* Setup the object
*
* Attached filters and actions to hook into WordPress
*/
function __construct( $options = array() )
{
add_filter('embed_oembed_html', array($this, 'modify_embed_output'), 9999, 3);
add_filter('wp_head', array($this, 'inline_css') );
}
/**
* Add Embed Container
*
* Wrap the video embed in a container for scaling
*/
public function modify_embed_output( $html, $url, $attr ) {
// Pattern for removing width and height attributes
$attr_pattern = '/(width|height)="[0-9]*"/i';
$whitespace_pattern = '/\s+/';
$embed = preg_replace($attr_pattern, "", $html);
$embed = preg_replace($whitespace_pattern, ' ', $embed); // Clean-up whitespace
$embed = trim($embed);
// Add container
$html = "<p class=\"embed-container\">$embed</p>\n";
return $html;
}
/**
* Embed CSS
*
* CSS needed to automatically resize embedded videos, method originally
* created by Anders M. Andersen at http://amobil.se/2011/11/responsive-embeds/
*/
function inline_css() {
?><style type="text/css">
.embed-container {
position:relative !important;
padding-bottom:56.25% !important; /* 16/9 ratio */
padding-top:30px !important; /* IE6 workaround*/
height:0 !important;
overflow:hidden !important;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
position:absolute !important;
top:0 !important;
left:0 !important;
width:100% !important;
height:100% !important;
}
</style><?php
}
}
$responsive_embeds = new ResponsiveVideoEmbeds();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment