I am trying to wrap any iframe/embed in my content with some Facebook Instant Articles friendly code (only for that feed). I have it working, but it adds this code to oEmbed output as well which adds in a wrapper that is not needed (since the Facebook Instant Articles already handles oEmbed embeds).

Basically, how can I get the wrap on iframes/embeds to happen before the oEmbed stuff happens?

Below is the code I have:

function wrap_iframe( $content ) {
    if (is_feed( INSTANT_ARTICLES_SLUG )) {
        // Match any iframes or embeds
        $pattern = '~<iframe.*</iframe>|<embed.*</embed>~';
        preg_match_all( $pattern, $content, $matches );
        foreach ( $matches[0] as $match ) {
            $wrappedframe = '<figure class="op-interactive"><iframe>' . $match . '</iframe></figure>';
            $content = str_replace($match, $wrappedframe, $content);
        return $content;
add_filter( 'the_content', 'wrap_iframe' );

WordPress embed the URLs on same filter with priority of 8

in /wp-includes/class-wp-embed.php

// Attempts to embed all URLs in a post
add_filter( 'the_content', array( $this, 'autoembed' ), 8 );

and you are parsing content after it with priority of 10 then defiantly you will get the parsed output.

You just need to do it early before WordPress embed URLs

add_filter( 'the_content', 'wrap_iframe', 5 );
  • This works perfect. Guess I should have known that it was just a matter of giving it a higher priority. Thanks! – KKranzo Apr 13 '16 at 19:33
  • Spoke too soon... after clearing the cache, etc. I noticed that it made the content empty for some reason when I viewed a regular post in my templates that were not in the feed (seems like the feed part worked fine though). – KKranzo Apr 13 '16 at 20:08
  • Do I need to add an else statement in the function to just return $content even if it is not a feed? – KKranzo Apr 13 '16 at 20:31
  • No need for else, just put the return $content; statement outside the if block. In filters value should be return always even if modified or not! @KKranzo – Sumit Apr 14 '16 at 4:21

There is a specific filter for this: embed_oembed_html.

add_filter('embed_oembed_html', function($html) {
    return '<figure class="op-interactive">'.$html.'</figure>';
}, 11); 

Source: Wordpress codex

Your Answer

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

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