Skip to content

Instantly share code, notes, and snippets.

@jester1979
Last active October 9, 2015 09:28
Show Gist options
  • Save jester1979/3478704 to your computer and use it in GitHub Desktop.
Save jester1979/3478704 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment