Since WordPress 5.5, WordPress has started enabling lazy loading on images. This was dramatically improved in WordPress 6.3.
At the same time, the default value of wp_omit_loading_attr_threshold
changed from 1 to 3, meaning the first 3 images will not be lazy loaded, and in fact will have fetchpriority=high
. This makes sense for a typical homepage or the first blog post, but less so for the 2nd or 3rd blog post on a page.
I wrote a filter to force enable lazy loading after the first blog post. This ensures that even if the first image is farther down the page, it will not have fetchpriority=high
.
// Lazy load all images after the first post
add_filter('wp_get_loading_optimization_attributes', function ($attrs, $tag, $attr, $context) {
if (is_admin() || !is_main_query()) {
return $attrs;
}
if ($tag !== 'img') {
return $attrs;
}
global $wp_query;
if ($wp_query->posts[0]->ID === get_the_ID()) {
return $attrs;
}
$attrs['loading'] = 'lazy';
$attrs['fetchpriority'] = null;
return $attrs;
}, 10, 4);