Using WordPress ‘post_class()’ PHP function

The post_class() WordPress PHP function displays the classes for the post container element.

Usage

post_class( $css_class, $post )

Example:

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

Parameters

  • $css_class (string|string[]) Optional. One or more classes to add to the class list. Default: ''
  • $post (int|WP_Post) Optional. Post ID or post object. Defaults to the global $post. Default: null

More information

See WordPress Developer Resources: post_class()

Examples

Add a single class

Add a single class to the post_class defaults:

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

Add multiple classes

Use an array to add multiple classes:

$classes = array( 'class1', 'class2', 'class3' );
?>
<div id="post-<?php the_ID(); ?>" <?php post_class( $classes ); ?>>

Specify a different post ID

To print post_class CSS classes for a post other than the current one, specify its ID (integer):

post_class( '', 22 );

Default usage in a theme file

This example shows the post_class template tag as commonly used in a theme file (such as single.php):

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

Add multiple classes as a string argument

A simple way to add multiple classes to the post_class defaults, is to just write them as a string argument:

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