1

I`m optimizing site with PageSpeed test tool.

How to remove lazy loading from 7 first thumbnails (featured images) in front page and categories? By default worpress lazy-loading from 4th image, but I need from 7th.. Can`t find solution.

This filter removes lazy loading from all images in whole website:

add_filter( 'wp_lazy_loading_enabled', '__return_false' );

This script removes from first 6 images, but only in post content (I need in categories and frontpage):

function add_responsive_class($content) {
    $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
    $document = new DOMDocument();
    libxml_use_internal_errors(true);
    $document->loadHTML(utf8_decode($content));
    $imgs = $document->getElementsByTagName('img');
    
    for ($i = 0; $i < min(6, $imgs->length); $i++) {
        $img = $imgs->item($i);
        $img->removeAttribute('loading');
    }
    $html = $document->saveHTML();
    return $html;
}
add_filter('the_content', 'add_responsive_class');

My thumbnail image code example:

<img width="248" height="248" src="wp-content/uploads/b-248x248.jpg" class="gal-thumbnail wp-post-image" decoding="async" itemprop="image" loading="lazy" 
wp-content/uploads/berniukas-300x300.jpg 300w, 
wp-content/uploads/b.jpg 800w" sizes="(max-width: 248px) 100vw, 248px">

Can You help me?

1 Answer 1

1

You would do this by filtering the threshold to change it from the default 3 to 6 via wp_omit_loading_attr_threshold:

See:

2
  • Super! You saved me!
    – uni uni
    Nov 8 at 19:20
  • @uniuni if this answered your question consider marking it as the correct answer by clicking the tick button under the voting controls
    – Tom J Nowell
    Nov 9 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.