Add wrapper to only youtube videos via embed_oembed_html filter function

I have a filter working to wrap embed_oembed links in a responsive wrapper. See code.

add_filter('embed_oembed_html', 'wrap_embed_with_div', 10, 3);

function wrap_embed_with_div($html, $url, $attr) { 
return '<div class="responsive-container">'.$html.'</div>';
}

The only problem is this also applies to everything else on the oembed list, i.e, twitter embeds, instagram, etc. I was trying to add an if statement, but have no luck. Basically, it would be great to just add this wrapper to video embeds like youtube/vimeo.
Here is what I got so far.

add_filter('embed_oembed_html', 'wrap_embed_with_div', 10, 3);

function wrap_embed_with_div($html, $url, $attr) {
if ($url == 'https://youtube.com'){ 
return '<div class="responsive-container">'.$html.'</div>';
}
else { 
return $html;
}
}

1 Answer
1

$url will contain the full URL to the embed source. E.g.: https://www.youtube.com/watch?v=_UmOY6ek_Y4, so you have to search within $url to see if the provider’s name appears:

add_filter( 'embed_oembed_html', 'wpse_embed_oembed_html', 99, 4 );
function wpse_embed_oembed_html( $cache, $url, $attr, $post_ID ) {
    $classes = array();
    
    // Add these classes to all embeds.
    $classes_all = array(
        'responsive-container',
    );
    
    // Check for different providers and add appropriate classes.
    
    if ( false !== strpos( $url, 'vimeo.com' ) ) {
        $classes[] = 'vimeo';
    }

    if ( false !== strpos( $url, 'youtube.com' ) ) {
        $classes[] = 'youtube';
    }
    
    $classes = array_merge( $classes, $classes_all );

    return '<div class="' . esc_attr( implode( ' ', $classes ) ) . '">' . $cache . '</div>';
}

Leave a Comment