Custom img filter :
//img Markup with LQ source, data-src and auto-size
function get_respimg( $attid ) {
$full_src = wp_get_attachment_url( $attid );
$alt = get_post_meta($attid, '_wp_attachment_image_alt', true);
//ignore if gif||svg
if (substr($full_src, -4) == '.gif' || substr($full_src, -4) == '.svg' ) {
return '<img src="'.$full_src.'" alt="'.$alt.'">';
}
$lowQuality = wp_get_attachment_image_src($attid, 'thumbnail')[0];
var_dump( $lowQuality );
echo '<br>';
$srcset = wp_get_attachment_image_srcset($attid);
return '<img class="lazyload" data-sizes="auto" src="' . $lowQuality . '" data-srcset="' . $srcset . '" alt="' . $alt . '">';
}
//Lazysize layGridder
function lazyload_images_filter($markup, $element){
return '<div class="lg-placeholder" style="padding-bottom:' . ($element->h/$element->w*100) . '%;">' . get_respimg($element->attid) . '</div>';
}
add_filter( 'lg_frontend_img', 'lazyload_images_filter', 10, 2 );
?>
Load Lazysize for this to work
function load_lazysize() {
wp_enqueue_script( 'lazysizes-js', "https://cdnjs.cloudflare.com/ajax/libs/lazysizes/2.0.6/lazysizes.min.js");
}
add_action( 'wp_enqueue_scripts', 'load_lazysize' );
What it does :
- Loads the thumbnail img as src first (me personnaly I load another image size 25px wide)
- Enables you to style images depending on loading state (
.lazyload
, .lazyloading
and .lazyloaded
) with the effect you desire : blur, opacity, translation
- Then loads the perfect image size with srcset and data-sizes="auto".
- If you want non-srcset compatible browser to show non-lowquality img, you can add
data-src="$theImageSizePreferToLazyloadInstead"