Skip to content

Instantly share code, notes, and snippets.

@wturnerharris
Created December 16, 2013 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wturnerharris/7989591 to your computer and use it in GitHub Desktop.
Save wturnerharris/7989591 to your computer and use it in GitHub Desktop.
Filter function for WordPress: this adds an onload attribute onto the img element for calls that use the post_thumbnail_html filter such as get_the_post_thumbnail() or the_post_thumbnail()
/**
*
* Filter the post thumbnail html adding a javascript onload attribute.
*
* @param html(string)
* @return string
*/
function filter_thumbnail_html($html, $attr = false) {
if (empty($html)) return $html;
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML($html);
$img_tags = $dom->getElementsByTagName('img');
foreach($img_tags as $img) {
$img->setAttribute('onload', 'imagine(this)');
$dom->appendChild($img);
if ( $attr !== false ) return $img->getAttribute('alt');
}
return $dom->saveHTML($img);
}
add_filter( 'post_thumbnail_html', 'filter_thumbnail_html', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment