Adding Youtube video to Instant Articles for WP plugin

The official plugin for adding Instant Articles support to a WordPress website is Instant Articles for WP created by Automattic & Facebook.

The problem

This plugin generates the XML needed by Facebook to enable the Instant Articles functionality for your website. Although it will include your external resources ( like a Youtube video ) by default if it’s placed in the main post content, adding it from a custom field isn’t that easy and you need to define custom functionality.

The easiest way of adding custom content is by hooking into the “instant_articles_transformed_element” filter and modifying the content directly.

Because the instant article is composed of multiple XML components you can’t just add the iframe to the content as that will get ignored in the final output or worse: throw errors.

Adding a video to the Instant Articles

The recommended way is to use the Facebook Instant Articles PHP SDK functions available from the plugin:

add_filter( 'instant_articles_transformed_element','m_add_video' );
function m_add_video ($instant_article) {
    
    // ideally you should check that the class exists,
    // but as the filter will only be called in the plugin it shouldn't be a problem
    $post_id = $GLOBALS['_POST']['post_ID'];
    $video_url = get_post_meta($post_id, 'video_url', true);
    
    if ( !empty($video_url) ) {

        // make a full reference to the class in the plugin
        $video = \Facebook\InstantArticles\Elements\Interactive::create();
        $video->withSource($video_url);
        $video->withWidth(560);
        $video->withHeight(315);
        $video->withMargin(Facebook\InstantArticles\Elements\Interactive::NO_MARGIN);
        $instant_article->addChild( $video );
        
    }
    
    return $instant_article;
    
}

This will add a new iframe reference at the end of the instant article, if you are looking to add it in the beginning ( before the post content ) you can use “unshiftChild” instead of “addChild“.

Important:

  • you must set both width and height if you use “withSource” or it will get ignored by the SDK as not valid
  • if you want to avoid setting a height for custom iframes you can send something in the “withHTML” method
  • setting the iframe source directly to player.vimeo.com doesn’t work for some reason. You’ll have to add the Vimeo videos using the full iframe code in the withHTML method.