Site logo

Archived topic

Add a custom class to featured images

8 replies · Started by Muhammad on February 5, 2023

Viewing posts 1–9 of 9

Hi there,

I want to add a custom class to my featured images, so that I can exclude them from lazyloading. I found some solutions through Google but they couldn't solve my issue. I have added my website URL in private info area for better understanding.

Hi David,

Yes, I am using the WPRocket. And where should I put this code?

function skip_lazy_class_first_featured_image($attr) {
global $wp_query;
if ( 0 == $wp_query->current_post ) {
$attr['class'] .= ' first-featured-image';
}
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'skip_lazy_class_first_featured_image' );

I have installed the code snippets plugin and added+activated the code just now. But still can't see the first-featured-image class in the source code for the featured image.

Hi there,

As you are using an image optimization plugin, it changes the image HTML format, the PHP code would not work.

Can you try adding the class directly to the dynamic image block? I'm not sure if it's gonna work with your image plugin, but give it a try.

https://www.screencast.com/t/vhVhOwp89mMq

Let me know :)

You're right, Ying. I added the class on dynamic image block. But now the class the added on the picture tag (the parent to img tag), not the actual img tag.

I have changed the settings of Image optimization plugin. Now it's using the img tag instead of picture tag.

Glad to hear that :)

This archived topic is closed to new replies.