post_class()WP 2.7.0

Display the classes for the post div.

1 time — 0.004188 sec (very slow) | 50000 times — 10.89 sec (slow) | PHP 7.0.2, WP 4.4.1

No Hooks.


null. Nothing (null).


post_class( $css_class, $post );
One or more classes to add to the class list.
Default: ''
Post ID or post object.
Default: global $post



#1 Basic example

Apply the function to the HTML container containing the post data:

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

We ended up with something like (let the post is in the 'dancing' category):

<div id="post-4564" class="post post-4564 category-48 category-dancing logged-in">

For this example, the following selectors should be used in CSS:

.post {
	/* styles for all posts */
.post-4564 {
	/* styles only for the post in ID 4564 */
.category-dancing {
	/* styles for all posts from the dancing category */

#2 Adding new classes

The function occupies the "class" attribute, so if we need to add our own class to the tag, we need to add it via function by simply writing it in the function parameter:

<div <?php post_class('class-name'); ?>>

As a result, we get

<div class="class-name post post-4564 category-48 category-dancing logged-in">

#3 Adding classes through a filter

To add the names of all the categories the post belongs to as classes, you can use this code:

add_filter( 'post_class', 'category_id_class' );
add_filter( 'body_class', 'category_id_class' );

// add category names as classes to body class and post class functions
function category_id_class( $classes ){
	global $post;

	foreach( get_the_category( $post->ID ) as $category ){

		$classes[] = $category->category_nicename;

		return $classes;

#4 Off-cycle use

If we want to get the classes of the specific post, but not the classes of the current-page-post, we can pass the second parameter which contains the ID of the post we need:

<div <?php post_class( '', $post_id ) ?> >

#5 Use an array to add multiple classes:

$classes = array(

<div <?php post_class( $classes ) ?> >

#6 Add multiple classes as string

A simple way to add multiple classes to the default class list, is to just write them space-separated:

<div <?php post_class( 'class1 class2 class3' ) ?> >


Since 2.7.0 Introduced.

post_class() code WP 6.5.3

function post_class( $css_class = '', $post = null ) {
	// Separates classes with a single space, collates classes for post DIV.
	echo 'class="' . esc_attr( implode( ' ', get_post_class( $css_class, $post ) ) ) . '"';