Wrap embed html code with a div for easy styling.
Last week a member on the WordPress Ireland facebook group asked:
Is there a function to change the iframe output and wrap a div around it for the shortcode when you insert a youtube url from the post editor?
I suggested looking at the filters in the oEmbed area of WordPress core. The next day another member posted example code that used the ‘embed_oembed_html‘ filter to add a div, with a special class for facebook and twitter embeds and another for other embeds.
I was a little concerned that the called filter function only used one of the three parameters being passed to it. It probably wasn’t a problem as PHP is loosely typed so would not complain about this. I also wondered if the code could break if the ‘twitter’ or ‘facebook’ strings were in the returned html but the embed wasn’t from either site.
I looked through the WordPress code code for ‘youtube’ and found the ‘wp_embed_handler_youtube‘ filter. I hoped to use this so that the div could be added only to YouTube videos without any need to check the incoming html or url. Unfortunately the code I wrote to do this never got called, regardless of whether the YouTube video url was within an ’embed’ shortcode or just in the content. I had to return to the original filter.
While the original gist searched the generated html, I search the url that was passed to the embed code. This eliminates the possibility of a false positive search result for when the generated html contains the search string. While the risk is low, I wanted to minimise it. During my experiments I noticed that the instagram embed html code contains the text from the instagram post. It is possible that one could reference youtube.com in that and thus trigger a false positive search result.
I decided to make my code easy to extend and maintain. When a YouTube video is found it simply adds a new class to the
$classes array. This array provides the html class values for the generated div. The code puts a div around the html of each embed.
stripos checks will allow targetting of additional embed origins.