Last active
May 11, 2020 02:25
-
-
Save huanyichuang/f3bb9d314e038d0bdca6759c26f52b02 to your computer and use it in GitHub Desktop.
Prepare WordPress post for Image LazyLoading by replacing the src Attribute
This file contains 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
<?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