I'm using W3 Total Cache plugin for my WordPress site. I've enabled Lazy Load setting option, but I want to disable the option for the specific post type. How can I hook and disable it?
3 Answers
According to the W3 Total Cache plugin author's website, you can prevent individual images from lazy loading if you add the image URLs to the "Exclude words" section of the User Experience > Lazy Loading section.
This is helpful when using page builders that do not give you direct access to the class attribute of the image tag (such as Elementor).
-
I was able to disable lazy load for images using class "skip-lazy", it didn't work for class "no-lazy" Commented Feb 15 at 10:33
This answer might be a bit too late but here goes: W3 Total Cache will skip lazy loading images that have class "no-lazy". This means that you can hook to the get_the_post_thumbnail() filter post_thumbnail_html and add the class to the image.
Here's an example:
/**
* Disable W3 Total Cache lazy load for post type "post"
*
* @param string $html
* @param int $post_id
* @param int $image_id
* @param string|int[] $size
* @param string|array $attr
*/
function _post_thumbnail_html( $html, $post_id, $image_id, $size, $attr ){
if( !empty( $html ) ){
$post = get_post( $post_id );
if( 'post' === $post->post_type ){
if( isset( $attr['class'] ) ){
$attr['class'] .= ' no-lazy';
}else{
if( !is_array( $attr ) ){
$attr = array();
}
$attr['class'] = 'no-lazy';
}
$html = wp_get_attachment_image( $image_id, $size, false, $attr );
}
}
return $html;
}
add_filter( 'post_thumbnail_html', '_post_thumbnail_html', 10, 5 );
-
According to the docs the class to use is now "skip-lazy". Commented Jan 25, 2023 at 18:29
You can use this filter,
function ar_lazyload_deactivate() { if ( is_singular( 'posttype name' ) ) { add_filter( 'do_rocket_lazyload', '__return_false' ); } } add_filter( 'wp', __NAMESPACE__ . '\ar_lazyload_deactivate' );
-
1It's wp rocket. It talking about w3 total cache. Is it using the same hook? Commented Jan 18, 2020 at 2:41