How to add a CSS class to the get_the_post_thumbnail() function in WordPress

To add a CSS class to the get_the_post_thumbnail() function in WordPress, you can use the $attr parameter. Here’s an example code snippet:

<?php
// Set the CSS class for the thumbnail
$thumbnail_class = 'my-custom-class';

// Get the post thumbnail with the custom class
if ( has_post_thumbnail() ) {
$thumbnail = get_the_post_thumbnail( null, 'thumbnail', array(
'class' => $thumbnail_class,
) );
echo $thumbnail;
}
?>

In this code, we first define a variable $thumbnail_class to hold the name of the CSS class we want to add to the thumbnail.

Then, we use the get_the_post_thumbnail() function to retrieve the thumbnail image with the thumbnail size, and we pass an array of attributes for the img tag through the $attr parameter. In this array, we set the class attribute to the value of $thumbnail_class.

You can replace my-custom-class with the name of your own custom CSS class. When you use this code in your WordPress template, the thumbnail image will have the specified CSS class applied to it.

Leave a Reply

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