,

Responsive embeds in WordPress

So a site I’ve been working on had embedded YouTube videos, which in it self is fine, except the site is responsive, and at times the YouTube clip would be either way too small, or too large depending on the format.
Most sites suggested using a plugin to achieve the responsive functionality, but this felt a bit overkill for two small CSS rules, and a class around the embedded content, that’s why I chose to use a filter on the_content in WordPress to add the wrappers without any input from the end user, greatly increasing usability in my opinion, as users shouldn’t be expected to input custom html code to make their site work.

The solution for the CSS I learnt from http://avexdesigns.com/responsive-youtube-embed/, so kudos to them for that, my implementation is as below;

.embed-container {
	floatleft;
	width100%;
	positionrelative;
	padding-bottom56.25%;
	padding-top30px;
	height0;
	overflowhidden;
}
.embed-container object,
.embed-container embed,
.embed-container iframe {
	positionabsolute;
	top0;
	left0;
	width100%;
	height100%;
}
<?php
/**
 * Filter for adding wrappers around embedded objects
 */
function responsive_embeds$content ) {
	$content = preg_replace"/<object/Si"'<div class="embed-container"><object'$content );
	$content = preg_replace"/<\/object>/Si"'</object></div>'$content );
	
	/**
	 * Added iframe filtering, iframes are bad.
	 */
	$content = preg_replace"/<iframe.+?src=\"(.+?)\"/Si"'<div class="embed-container"><iframe src="\1" frameborder="0" allowfullscreen>'$content );
	$content = preg_replace"/<\/iframe>/Si"'</iframe></div>'$content );
	return $content;
}
add_filter'the_content''responsive_embeds' );

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.