Created
December 16, 2013 16:11
-
-
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()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* 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