Featured Image for How to add custom CSS class to WordPress post  featured images

How to add custom CSS class to WordPress post featured images

Published on July 29, 2024 6:12 pm

Last updated: August 1, 2024

It’s often needed to add custom CSS classes to the thumbnail aka featured image of a post for various reasons. One of the most queried reason is to exclude post featured images from lazy loading and always preloading them.
We can do it with 1 line of PHP code .

<?php 

  add_filter( 'post_thumbnail_html', function($html){
    return preg_replace('/class=([\'"])/','class=$1featured-image ',$html);
  },10,1);
  
  ?>
 

Now we can use featured-image classname wherever we need e.g, we can now add custom styles to all the post featured images, to do that we need to add the CSS rules to the featured-image class.

.featured-image{
  border-radius: 8px;
}

Found this post helpful ? Share it now and stay tuned for more such useful content 😉

Note: Add  code snippets to the functions.php file of the active theme or child theme of your website or use a plugin like code snippets. 
Proloy Bhaduri
Full Stack WordPress and WooCommerce Developer having 8+ years of experience

1 comment

Leave your comment