Hooking into WordPress OEmbed for Responsive Video
Embedding videos in WordPress is simple thanks to WordPress excellent support for oEmbed enabled content on a number of popular sites. Just pasting in a video link is enough – WordPress handles turning it into an embedded player. This is great for non-technical users, as they can avoid having to grab
iframe embed code or use extra plugins just to handle embedding media. Front-end developers will know that there is an issue with the approach – responsiveness. I am going to show you how you can add functionality to your theme to make WordPress-generated oEmbed video players responsive using WordPress’
embed_oembed_html filter rather than having to monkey-patch it with JS after the page load.
If you are already familiar with techniques for making fixed-aspect ratio responsive elements, you can skip to the solution. If not, here is a primer on the topic.
Making iFrame Embeds responsive
Most video sites embeds are fixed aspect ratio iframes that are not responsive on their own. This is a problem that is solved by wrapping the iframe element with another element and a few CSS rules. Front-end frameworks like Bootstrap and Foundation use similar methods for this. In short, they use a relatively positioned element with 100% width, 0% height and a padding-bottom defined as percentage to create a responsive element with fixed position. The iframe inside is then absolutely positioned top & left with width and height set to 100%, giving it the same aspect ratio as the parent. In the pen below, you can see the basic idea. Notice how I am calculating padding-bottom value that forces the aspect ratio based on the height & width attribute values from the youtube iframe embed code – this is the key concept.
Using the embed_oembed_html filter
Here is the solution, composed of the PHP hooking into the WP filter, and a bit of SCSS to go with it. The filter intercepts the oEmbed html output, wrapping it in a new element that has a dynamically calculated aspect ratio to create responsive videos. The aspect ratio is calculated based on the width and height attributes of the iframe in the embed html – if they are not present, the filter leaves the html unchanged. Read comments for a line by line explanation! If you want, you can also view/bookmark the gist itself 🙂
As I mentioned in the big old
TODO in the comments, this could be used to do different things to different iframes depending on source. The same regex that is used to grab the width/height attributes could be used to provide us with the
src attribute and we could add different markup and/or classes accordingly. Hopefully you find this useful!