Add class to WordPress post in the loop

You can use the post_class filter to add a class to the WordPress post in the loop if you are using the post_class function. If you want to add a post class to your post in the loop, simply add the following code in your loop.

post_class()

But sometimes you don’t want to change the archive or single post and page codes. You can use the post_class filter to add the class to your post.

function hs_post_classes( $classes, $class, $post_id ) {
 
	if( is_single() ) {
		$classes[] .= 'hs-single-post';
	} else if ( is_page() ) {
		$classes[] .= 'hs-page';	
	} else {
		$classes[] .= 'main-post';
	}
     
    return $classes;
}

add_filter( 'post_class', 'hs_post_classes', 10, 3 );
Shopping Cart