WordPress post_class() Function

Beginner
6 min read
Updated: Nov 2026
3 examples
Prints a class attribute

Definition

In WordPress, post_class() prints a class attribute for one post. You put it on the article or div that wraps each post in The Loop.

The classes include the post ID, post type, status, format, and its categories and tags. This gives you many hooks for CSS.

Syntax

A few ways to call post_class().

WordPress
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
CallWhat it does
post_class()Print the default classes.
post_class( 'card' )Add your own class.
post_class( 'card', 12 )Use the classes of the post with ID 12.
get_post_class()Return the classes as an array instead of printing.

It prints the whole class="..." attribute, so do not add class= yourself on the same tag.

Full declaration
WordPress
post_class( string|string[] $css_class = '', int|WP_Post $post = null ): void

Parameters

ParameterDescription
$css_classstring|string[]. One or more extra classes. Default is empty.
$postint|WP_Post. The post ID or object. Default is the current post.

Return Value

Return ValueDescription
voidNothing is returned. The class attribute is printed.

WordPress Examples

Three short examples. Each one shows the code and what it prints.

Example 1 — Add it to each post

Use it on the article tag inside The Loop.

WordPress
<?php while ( have_posts() ) : the_post(); ?>
  <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <h2><?php the_title(); ?></h2>
  </article>
<?php endwhile; ?>

How It Works

  1. the_ID() makes a unique id for each post.
  2. post_class() prints classes for the post type, status, and categories.
  3. Use these classes in your CSS, for example .category-news.

Example 2 — Add your own class

Add a class to every post card.

WordPress
<article <?php post_class( 'card' ); ?>>

How It Works

  1. Your class is added after the default classes.
  2. Pass an array to add several classes.
  3. You can now style .card once for all posts.

Frequently Asked Questions

It prints a class attribute for one post with classes such as post ID, post type, status, and terms.
On the article or div that wraps each post inside The Loop.
post_class() styles one post. body_class() styles the whole page and goes on the body tag.
Pass it as an argument, like post_class( 'card' ), or use the post_class filter.
Yes. Use get_post_class(). It returns an array.

Browse all post functions

Open the functions index for simple guides with examples and FAQs.

Post Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful