Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krishna19/568ed22cb0b4fad5f907862e019c56d6 to your computer and use it in GitHub Desktop.
Save krishna19/568ed22cb0b4fad5f907862e019c56d6 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