How To Add a Custom Class To The Post Thumbnail (Featured Image) in WordPress

Home » Blog » WordPress Development » How To Add a Custom Class To The Post Thumbnail (Featured Image) in WordPress

If you want to customize the look and feel of your post thumbnails, you might want to add a custom CSS class to them.

All you need to do to accomplish this is add the following code in your theme wherever a post listing Loop is used:

if (has_post_thumbnail()) { 
   the_post_thumbnail('medium', array('class' => 'my_custom_class'));

This code simply displays the thumbnail if there is a thumbnail. The first argument of the_post_thumbnail is the size of the thumbnail to be displayed. WordPress crops thumbnails you upload into many different sizes. If you want the full-size image, then use ‘full’. The second argument of this function takes an array of options. The only option we are interested in is the class option which adds a custom CSS class to the thumbnail/featured image. Whatever class name you put in place of my_custom_class will be added to the <img/> element of the thumbnail.

You will want to add this code to all the PHP files of your theme where a Loop is used to display blog posts. This might include index.php, blog.php, archive.php, and some other custom pages.

If your theme already has a call to the_post_thumbnail, replace the existing one with the above code.

Leave a Reply

Your email address will not be published. Required fields are marked *

Register an account to save your snippets or go Pro to get more features.