Skip to content

Instantly share code, notes, and snippets.

@tyohan
Created November 14, 2017 10:29
Show Gist options
  • Save tyohan/bad781f5b5c29d0fc920e30a3d777d18 to your computer and use it in GitHub Desktop.
Save tyohan/bad781f5b5c29d0fc920e30a3d777d18 to your computer and use it in GitHub Desktop.
<?php
function lazyloadImages($html) {
$matches = array();
preg_match_all( '/<img[\s\r\n]+.*?>/is', $html, $matches );
$search = array();
$replace = array();
foreach ( $matches[0] as $imgHTML ) {
// don't do the replacement if the image is a data-uri
if ( ! preg_match( "/src=['\"]data:image/is", $imgHTML ) ) {
$placeholder_url_used = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
if( preg_match( '/class=["\'].*?wp-image-([0-9]*)/is', $imgHTML, $id_matches ) ) {
$img_id = intval($id_matches[1]);
}
// replace the src and add the data-src attribute
$replaceHTML = preg_replace( '/<img(.*?)src=/is', '<img$1src="' . esc_attr( $placeholder_url_used ) . '" data-lazy-type="image" data-lazy-src=', $imgHTML );
// also replace the srcset (responsive images)
$replaceHTML = str_replace( 'srcset', 'data-lazy-srcset', $replaceHTML );
// replace sizes to avoid w3c errors for missing srcset
$replaceHTML = str_replace( 'sizes', 'data-lazy-sizes', $replaceHTML );
// add the lazy class to the img element
if ( preg_match( '/class=["\']/i', $replaceHTML ) ) {
$replaceHTML = preg_replace( '/class=(["\'])(.*?)["\']/is', 'class=$1lazy lazy-hidden $2$1', $replaceHTML );
} else {
$replaceHTML = preg_replace( '/<img/is', '<img class="lazy lazy-hidden"', $replaceHTML );
}
$replaceHTML .= '<noscript>' . $imgHTML . '</noscript>';
array_push( $search, $imgHTML );
array_push( $replace, $replaceHTML );
}
}
$html = str_replace( $search, $replace, $html );
return $html;
}
add_filter('the_content', 'lazyloadImages' );
add_filter('post_thumbnail_html','lazyloadImages');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment