With newer versions of WordPress, YouTube auto oEmbeds. On this particular site I am working on, I need a unique div
wrapper around the embedded iframe
. I had a look in my functions.php
but couldn't see anything related to YouTube. Where would I find the code I need to add my extra html?
-
I like this question but yes, needs expansion.– Brad DaltonCommented Sep 25, 2014 at 20:33
2 Answers
Personally, I found the oembed_dataparse
filter pretty fiddly to use; sometimes it worked, sometimes it didn't; and when used in conjunction with custom TinyMCE instances, it seems as though the added wrapper was hard-baked into the content rather than added via the filter at output.
I found the embed_oembed_html
filter much more reliable and works every time:
function vnmFunctionality_embedWrapper($html, $url, $attr, $post_id) {
return '<div class="embedwrapper">' . $html . '</div>';
}
add_filter('embed_oembed_html', 'vnmFunctionality_embedWrapper', 10, 4);
Note that this will wrap all oEmbeds. If you wanted to target YouTube specifically:
function vnmFunctionality_embedWrapper($html, $url, $attr, $post_id) {
if (strpos($html, 'youtube') !== false) {
return '<div class="youtubewrapper">' . $html . '</div>';
}
return $html;
}
-
Your answer works as well … Personally I'd prefer to target providers by name then my a guess on the url. Still +1 for the alternative. If you are unsure if it works: just put an
exit
on the other answers filter callback and you will see it working.– kaiserCommented Aug 21, 2015 at 0:03 -
@kaiser Fair point; I hadn't actually analysed the parameters here in much detail; much like the OP, I only needed it to work for YouTube, and I knew what the input was going to be. But this will fall over when presented with shortened URLs and such.– indextwoCommented Aug 21, 2015 at 10:08
-
Just have the problem that I can't get any output there as well … as live goes :P– kaiserCommented Aug 21, 2015 at 12:14
Make a custom plugin for your site, put this code in it.
add_filter('oembed_dataparse','oembed_youtube_add_wrapper',10,3);
function oembed_youtube_add_wrapper($return, $data, $url) {
if ($data->provider_name == 'YouTube') {
return "<div class='whatever'>{$return}</div>";
} else {
return $return;
}
}
Note: The filter runs when the data is gathered from the oembed provider. So, if you already embedded the post, and the embed data is cached, this won't modify it.
-
-
Edit – I'm not sure if this just works out of the box. Either I just got a heavy caching problem or the filter (which runs at the end of
WP_OEmbed
s constructor in core) only runs for fresh posts. Can't backtrace that one. @Otto Any hints?– kaiserCommented Aug 21, 2015 at 13:59 -
2The filter runs when the data is gathered from the oembed provider. So, it you already embedded the post, and the embed data is cached, this won't modify it.– OttoCommented Aug 21, 2015 at 17:26
-
-