I want to add a custom class for the embed_oembed_html filter (iframe).

NOTE 1: using str_replace will remove the anther classes so it's not useful. NOTE 2: I need to add the custom class directly into the ifram tag not add the full iframe code into another tag like <div>.

  • "using str_replace will remove the anther classes so it's not useful" How are you doing str_replace? It's perfectly possible to add text with str_replace, not just replace it. Nov 29, 2017 at 7:25
  • @JacobPeattie this is my code: $cache = str_replace("<iframe", '<iframe class="lazy-load"', $cache); and it's removed the anther classes
    – Trello
    Nov 29, 2017 at 7:40
  • What does the original HTML look like? Update the original question with this information. Nov 29, 2017 at 7:47
  • @JacobPeattie It's a blog post, My posts always have images, videos and iframes.
    – Trello
    Nov 29, 2017 at 7:52
  • No, the normal embed HTML that's generated that you're trying to change. Nov 29, 2017 at 7:53

1 Answer 1


You can't just add a class because WordPress doesn't know anything about the existing classes or have any control over them, the way it does posts and nav items. This is because the HTML comes from the 3rd party raw.

So to replace the class you need to use str_replace(). You can use it to add a class, or any text, by doing it something like this:

$cache = str_replace( '<iframe class="existing-class ', '<iframe class="existing-class lazy-load ', $cache );

But that example will only work A. If the embed code is an iframe (which isn't always guaranteed) and B. class="" is the first attribute in the tag.

This means exact string to replace is going to differ based on the original HTML, which will be different for every provider. Inside your filter you'll need to check the source and do a different str_replace() to accommodate all the providers you need to support with this class:

function wpse_287229_embed_html( $cache, $url, $attr, $post_ID ) {
    if ( 
        strpos( $cache, 'youtube.com' ) !== false || 
        strpos( $cache, 'youtu.be' ) !== false 
    ) {
        $cache = str_replace( '<iframe ', '<iframe class="my-class" ', $cache ); // YouTube doesn't have a class on its iframe.

    if ( strpos( $cache, 'soundcloud.com' ) !== false ) {
        // str_replace optimised for SoundCloud here.

    // etc.

    return $cache;
add_filter( 'embed_oembed_html', 'wpse_287229_embed_html', 10, 4 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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