Categories
Responsive Design Tutorials WordPress

Automatic responsive videos in WordPress with oEmbed, FitVids and a little PHP magic

Automaitc responsive videos in WordPress with oEmbed, FitVids and PHP
UPDATE: I’ve added a 4th step to the list to remove automatic inline styles from being inserted when embedding videos.

If you’re using a responsive theme on your WordPress site (or you’ve built a responsive theme) and you’ve added YouTube, Vimeo or other videos using oEmbed you will undoubtedly have noticed those videos do not resize with the rest of the frame. And that’s a royal pain. Fortunately there are solutions out there that can fix this, but they are a little tricky to implement. In this tutorial I’ll share with you a method for making the process automatic so you don’t have to worry about it.

The Problem

Responsive themes use percentage values, media queries and other coding magic to make the content resize to fit the size of the window. But when you embed videos from YouTube etc using the built in oEmbed function in WordPress (i.e. just paste in the URL to the video and it appears automatically) that video is inserted with a fixed width and height. As a result when the rest of the page resizes to fit the window, the video stays the same size causing all sorts of problems. This is sub optimal.

FitVids to the rescue… almost

Realizing this is a frustrating problem Chris Coyier and Paravel created a clever little jQuery plugin called FitVids that when installed automatically resizes videos along with the rest of the content. FitVids attaches to specified containers and forces the video iframes within these containers to resize along with it. Very clever and it works exactly as expected. However, to make this work you have to wrap the video in a container with a specified class. So if you want to use the oEmbed method you have to go to HTML view, create a div with a class and then put the URL inside it. Which kind of takes away the whole point of using oEmbed which is simplicity.

The Solution

What is needed is a function that automatically wraps all oEmbed videos in a div with the correct class that applies FitVids so all the user has to do is paste in the link to the video and then WordPress does the rest. And that’s just what we’re going to do:

Step 1: Enqueue FitVids

Go download FitVids.js from GitHub and add the jquery.fitvids.js file to your theme. I place all my JavaScript files in a sub-folder called ‘js’ for simplicity. Then we need to enqueue the script and associate it with jQuery. This is done in functions.php:


<?php 
// Add FitVids to allow for responsive sizing of videos
function your_theme_fitvids() {
	if (!is_admin()) {

		wp_register_script( 'fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array('jquery'), '1.0', true);    	
		wp_enqueue_script( 'fitvids');
	}
}

add_action('init', 'your_theme_fitvids');
?>

This function loads the jquery.fitvids.js file along with the packaged version of jQuery that comes with WordPress whenever a page is loaded.

Step 2: Create a function to target the videos

To make FitVids work you need to add a JavaScript function targeting a specific class. The function looks like this:


<?php
add_action('wp_footer', 'add_fitthem');
    	
function add_fitthem() { 
	    	jQuery(document).ready(function() {
    			jQuery('.video').fitVids();
    		});
}

All that happens here is the action is loaded in the footer (so it doesn’t slow down the population of the page itself and allows the videos in the iframes to load properly). It then appends the function to the .video class so that any video inside a div with the class video will be scaled to size.

This function is combined with the previous function so they get called at the same time. The resulting function looks like this:


<?php
// Add FitVids to allow for responsive sizing of videos
function your_theme_fitvids() {
	if (!is_admin()) {

		wp_register_script( 'fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array('jquery'), '1.0', true);    	
    	wp_enqueue_script( 'fitvids');
    	add_action('wp_footer', 'add_fitthem');
    	
    	function add_fitthem() { 
		    	jQuery(document).ready(function() {
	    			jQuery('.video').fitVids();
	    		});

	    }
	}
}

add_action('init', 'your_theme_fitvids');

Step 3: Automatically wrap oEmbed videos in a div with a class

The last step is to change the oEmbed output so that it automatically wraps the video iframe in a div with the class .video. This is done using a filter:


<?php
// Automatically add FitVids to oembed YouTube videos
function your_theme_embed_filter( $output, $data, $url ) {

	$return = '<div class="video">'.$output.'</div>;
	return $return;

}
add_filter('oembed_dataparse', 'your_theme_embed_filter', 90, 3 );
?>

This function grabs the output of the oembed_dataparse function (the one that creates the final code when you paste in a video URL) and wraps it in the correct div.

Step 4: Set Maximum Embed Size to 0

To get everything to work properly you have to go to Settings -> Media and set both width and height under Maximum Embed Size to 0. If you have a value in either of these fields, WordPress will include inline style code to constrain the size of the video and as a result the automatic resizing will not work.

That is all! When you add new videos to posts and pages using the oEmbed function, they are not automatically wrapped in the correct div and class and FitVids is applied. And voila: Your videos are responsive.

Caveat: These functions are not recursive!

The only catch with this process is that it is not recursive. By that I mean it doesn’t automatically work on videos that have already been embedded on your site. That is because the oembed_dataparse() function is called the when the post is published or updated. As a result, the function has already been run on old content and to apply the new div and class you have to re-run it. Fortunately that just means going in and clicking the Update button for each of the posts that have oEmbed videos in them, but if you have hundreds of videos you may want to consider doing some sort of database search/replace action.

To avoid the recursive problem I suggest you add this function to your theme at the very beginning and be done with it. That way as you populate your site the all your videos will be responsive.

Comments? Questions? Problems?

Got something to say? Leave a comment below.