WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 1 down vote accepted

try jQuery

$('iframe').wrap('<div class="wrapper" />');
share|improve this answer
This actually ended up being a simpler and more useful solution later after realizing that the php function was targeting too broad of a spectrum of iframes thoughout the site. – Mr.Brown Sep 6 '12 at 16:04
Of course this won't work if the browser has JavaScript disabled. – Craig Oct 14 '15 at 6:15

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);
share|improve this answer
If I am not wrong, for the filter to work, the last line should be: add_filter( 'embed_oembed_html', 'wrap_embed_with_div', 10, 4 ); – its_me Dec 3 '13 at 20:07
The last parameter in add_filter is accepted_args, which is an integer indicating the number of arguments accepted by the function, which in this case is 3. – user23385 Feb 10 '14 at 17:28

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');
share|improve this answer
Apologies for the late response, Ive away for work...this looks very promising, Ill give it a go and report back. – Mr.Brown Aug 18 '12 at 1:27
This works great, but is there any way to limit the wrapper to only output once after detecting the first iframe or embedded object?... – Mr.Brown Aug 18 '12 at 2:21
You could use preg_match instead of preg_match_all to only get one result. Or rewrite the foreach to break after the first iteration. Or not use a foreach and just get the first match ($match = $matches[0]). Just make sure you check if you've gotten any matches first. – pbd Aug 18 '12 at 10:52
Hmmm..interesting, thanks for the tip! – Mr.Brown Aug 19 '12 at 3:28
Thanks! Worked like a charm and fixed my problem :) – Ihor Vorotnov Mar 7 '14 at 15:32

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.