I need to wrap a div around all YouTube embeds in posts on our WP site.

  • WordPress version is 4.9.6

  • The posts in question are WooComerce products

  • Videos are being embedded by simply pasting a YouTube url in the post content.

In the code below lr_setup_embed_plugin() is definitely called because renaming that function causes an error, but the oembed_dataparse filter apparently isn't running because oembed_youtube_add_wrapper() is not called.

I have tried putting this code in functions.php and also in a plugin.

function oembed_youtube_add_wrapper($html, $data, $url) {

    if ($data->provider_name == 'YouTube') {
        return "<div class='whatever'>{$html}</div>";
    } else {
        return $html;

function lr_setup_embed_plugin(){
  add_filter('oembed_dataparse', 'oembed_youtube_add_wrapper', 0, 2);

add_action( 'after_setup_theme', 'lr_setup_embed_plugin' );
  • It's probably not the issue, but you shouldn't need the lr_setup_embed_plugin() function at all. You only need the oembed_youtube_add_wrapper() function and the add_filter(). – Jacob Peattie Apr 29 '19 at 12:32
  • @JacobPeattie I had it without the after_setup_theme action wrapper to start with (which didn't work) and read somewhere that filters had to be added after theme setup otherwise they would have no effect. – Ade Apr 29 '19 at 13:41
  • Maybe in rare cases for a specific filter or two, that I can't think of, but as a general rule that is not accurate. Generally you should add filters as early as possible. Usually the only instances that you'll need to defer an action like this is if you want to remove an action. You can only remove actions after they're added, so you'll often have to remove them from within another hook that runs later. – Jacob Peattie Apr 29 '19 at 14:01
  • OK good to know. Well in either case oembed_dataparse is not running my function despite there being a YouTube URL in the post content that is being automatically converted to an embedded IFrame. I solved it in 5 minutes with a jQuery workaround, but WordPress is just stubbornly refusing to cooperate. – Ade Apr 29 '19 at 14:06
  • I just copied your code exactly and it worked just fine. The YouTube embed is wrapped in a div with the class whatever. – Jacob Peattie Apr 29 '19 at 14:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.