Site logo

Archived topic

Remove loading="lazy" attribute from Featured Images

7 replies · Started by Muhammad on February 7, 2023

Viewing posts 1–8 of 8

Hi there,

Is there any way I can remove the loading="lazy" attribute from the featured images on single post. I've excluded my featured images from lazy loading through WP Rocket and the setting didn't appear to be working. When I contacted their support, they said that their plugin is working fine and it's the most probably the theme that's adding this attribute in the source code.

Anyways, I've found these two results through Googling https://generatepress.com/forums/topic/remove-loadinglazy-tag-for-featured-images/
https://generatepress.com/forums/topic/how-to-resize-featured-image-on-mobile/#post-1858309

But I don't know if the code mentioned in those posts will work for me. Or where should I put the code?

Hi there,

Can I see one of your post with featured image?

I have added my post URL in private info field.

It looks like you've already been using some custom functions to add the first-featured-image class to the featured image.

Can you try adding the first-featured-image class to WP rocket's exclusion list?

I have already done that. And according to WP Rocket, this image is not being lazy loaded. But somehow the source code is still having the loading="lazy" attribute that's causing my core web vitals score to drop slightly.

This is what actually they said:

".......As you can see in this screenshot, there are no lazyloaded class, data-ll-status="loaded" , <noscript> tag, which means that the image is not lazy loaded by WP Rocket.

But yes, the attribute loading="lazy" is present, and this is triggering the PageSpeed to warn you that the image is lazy loaded. However, attribute loading="lazy" is not added by WP Rocket.
This is very likely added by the theme"

I see,then it's likely being lazyloaded by WP.

Try adding this PHP code to remove the lazyload attribute from the image with first-featured-image class :

add_filter( 'wp_get_attachment_image_attributes', 'remove_lazy_load_attribute', 10, 3 );

function remove_lazy_load_attribute( $attributes, $attachment, $size ) {
	if ( isset( $attributes['class'] ) && strpos( $attributes['class'], 'first-featured-image' ) !== false ) {
		unset( $attributes['loading'] );
	}

	return $attributes;
}

I added the code and now this attribute is removed. Thanks for the help

You are welcome   :)

This archived topic is closed to new replies.