Skip to content

Instantly share code, notes, and snippets.

@huanyichuang
Last active May 11, 2020 02:25
Show Gist options
  • Save huanyichuang/f3bb9d314e038d0bdca6759c26f52b02 to your computer and use it in GitHub Desktop.
Save huanyichuang/f3bb9d314e038d0bdca6759c26f52b02 to your computer and use it in GitHub Desktop.
Prepare WordPress post for Image LazyLoading by replacing the src Attribute
<?php
/**
* Lozad
* Attribute replacement refernce from: https://gist.github.com/ahmadassaf/9332846
*/
function faster_replace_img_src( $content ){
if ( function_exists( 'is_amp_endpoint' ) && ! is_amp_endpoint() ) {
$html = preg_replace_callback( '#(<img\s[^>]*src)="([^"]+)"#' , 'callback_img' , $content );
$html = preg_replace( '/(<img\s[^>]*)class="(.*)"/', '$1 class="lozad $2"' , $html );
$html = preg_replace( '/(<img\s[^>]*)srcset="(.*)"/', '$1 data-srcset="$2"' , $html );
// $html = preg_replace( '/(<img\s[^>]*)class="(.*)"srcset="(.*)"/', '$1 class="lozad $2" data-srcset="$3"', $html );
return $html;
} else {
return $content;
}
}
function callback_img( $match ) {
list( , $img, $src) = $match;
return "$img=\"$preloading_image\" data-src=\"$src\" ";
}
add_filter( 'the_content', 'faster_replace_img_src' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment