jester1979
8/26/2012 - 12:45 PM

Filter WP's oEmbed output

Filter WP's oEmbed output

<?php

add_filter( 'embed_oembed_html', 'my_embed_filter', 10, 3 );
/**
* function for filter 'embed_oembed_html' it echo's a iframe-tag with it's src empty. the src is kept in data-src so javascript can put in the src-attr on a later moment. (e.g. after a cookie-check)
*
* @author Floris P. Lof
* @params String $html the ready made html received from an external API (like Twitter, Youtube, Vimeo)
* @params String $url the original URI with WP's oEmbed called the external API
* @params Array $attr extra attributes (width height)
* @return String $html the rendered html-code
*/
function my_embed_filter( $html, $url, $attr ) {

    //load the html created by the oEmbed-service
    $document = new DOMDocument();
    //error suppression needed here
    @$document->loadHTML( $html ); 
    
    //list the iframes and parse them
    $lst = $document->getElementsByTagName( 'iframe' ); 
    for ( $i = 0; $i < $lst->length; $i++ ) {
        $iframe= $lst->item( $i );
		
        $attr_src_value = $iframe->attributes->getNamedItem( 'src' )->value;
        //empty the 'src'-attribute
	$iframe->attributes->getNamedItem( 'src' )->value = '';	
						
        //create a new 'data-src'-attribute
	$data_src_attr = $document->createAttribute( 'data-src' ); 
        //copy the 'src'-value to our new 'data-src'-attribute
	@$data_src_attr->value = $attr_src_value; 
        //append it as a child to our iframe
	$iframe->appendChild( $data_src_attr );	
				
    }
    //save our domdoc back to html 
    $html = $document->saveHTML(); 
   
    return $html; 
}