How to wrap an element around an iframe or embed in content automatically?

Id like to have wordpress automatically wrap a div around any iframe or embed when they are used in the_content…how might this be achieved?

Related posts

Leave a Reply

3 comments

  1. Here’s the solution I used:

    function wrap_embed_with_div($html, $url, $attr) {
    
         return '<div class="video-container">' . $html . '</div>';
    
    }
    
     add_filter('embed_oembed_html', 'wrap_embed_with_div', 10, 3);
    
  2. With WordPress filters. Add this to your functions.php:

    function div_wrapper($content) {
        // match any iframes
        $pattern = '~<iframe.*</iframe>|<embed.*</embed>~';
        preg_match_all($pattern, $content, $matches);
    
        foreach ($matches[0] as $match) {
            // wrap matched iframe with div
            $wrappedframe = '<div>' . $match . '</div>';
    
            //replace original iframe with new in content
            $content = str_replace($match, $wrappedframe, $content);
        }
    
        return $content;    
    }
    add_filter('the_content', 'div_wrapper');