Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DvdGiessen/3776595 to your computer and use it in GitHub Desktop.
Save DvdGiessen/3776595 to your computer and use it in GitHub Desktop.
Filter WP's oEmbed output
<?php
/**
* Implementation for WP filter 'embed_oembed_html'.
* Modifies any iframes in the oEmbed's HTML to use a
* empty src-attribute, storing the original value in
* the data-src-attribute. A small piece of JavaScript
* can restore the src-attribute later.
* This is particularly useful for example to prevent
* external sites from setting cookies without the
* user's permission (EU/NL cookie law).
*
* @author Daniël van de Giessen
* @author Floris P. Lof
* @params string $html The HTML source received from an external API
* (like Twitter, YouTube, Vimeo), in UTF-8 encoding.
* @params string $url The original URI which WP's oEmbed used to call
* the external API.
* @params array $attr Extra attributes (such as width or height).
* @return string The HTML source with all iframe's src-tags moved
* to the data-src-attribute.
*/
function my_embed_filter($html, $url, $attr) {
// Create a new DOMDocument
$document = new DOMDocument();
// Load the HTML into the DOMDocument
@$document->loadHTML('<html><body>' . $html . '</body></html>');
// Loop over every iframe in the document
foreach($document->getElementsByTagName('iframe') as $item) {
if($item instanceof DOMElement && $item->hasAttribute('src') && !$item->hasAttribute('data-src')) {
// Save the src-attribute's value in the data-src-attribute
$item->setAttribute('data-src', $item->getAttribute('src'));
// Empty the src-attribute
$item->setAttribute('src', '');
}
}
// Save the modified HTML, extract the original code part and return it
return preg_replace('/^.*<body>(.*)<\/body>.*$/msi', '$1', $document->saveHTML());
}
// Add the filter
add_filter('embed_oembed_html', 'my_embed_filter', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment