Select Page

In this article, I will share with you a simple way to add a custom CSS class to your posts when they have a featured image. This can be done by adding a hook to your theme’s functions.php file.

When you set a featured image on a post, WordPress will automatically add a class to the post’s HTML element. The class is ” has-post-thumbnail “. You can use this class to style the post differently if it has a featured image set. For example, you could display the featured image above the title, or give it a different background color.

For example, this code will add a red background to any posts that have a thumbnail:

.has-post-thumbnail{ background: red; }

To add a custom CSS class to a post if it has a featured image set, you can add a filter to the post_class() function. This function is used to output the post classes, so we can just add our own class to the array of classes it outputs.

Here’s how you can do it:

function custom_class_posts_with_featured_image( $classes ) {
    if ( has_post_thumbnail() ) {
        $classes[] = 'has-featured-image';
    } return $classes;
}
add_filter( 'post_class', 'custom_class_posts_with_featured_image' );

In this example, a custom post class is added to any post with a featured image.

This filter can be used to add a class to every post on the site or to restrict the class to a specific post type, category, or other taxonomy.