WordPress theme authors who want to have finer css control options for their post styling, have the post_class function available. When the post_class function is added to a tag within the loop, for example <div <?php post_class(); ?> >, it will print out and add various post-related classes to the div tag. It can also be used outside the loop with the optional post_id parameter. This function is typically used in the index.php, single.php, and other template files that feature hierarchical post listings.

If you would prefer to have the post classes returned instead of echoed, you would want to use get_post_class(). Note: get_post_class() does not return a string, but an array that must be processed to produce text similar to what is echoed by post_class().

For css classes intended to help target entire pages, see body_class(), and for classes targeting comment listings, see comment_class().

post_class() 描述


The post_class may include one or more of the following values for the class attribute, dependent upon the pageview.

  • .post-id
  • .post
  • .attachment
  • .sticky
  • .hentry (hAtom microformat pages)
  • .category-ID
  • .category-name
  • .tag-name
  • .format-name

post_class() 用法


How to pass parameters to tags with PHP function-style parameters


(string or array) (可选) One or more classes to add to the class attribute, separated by a single space.

默认值: null


(int) (可选) An optional post ID, used when calling this function from outside The Loop

默认值: null

post_class() 参数



The following example shows how to implement the post_class template tag into a theme.

The actual HTML output might resemble something like this for a post in the "dancing" category:

In the WordPress Theme stylesheet, add the appropriate styles, such as:

Adding More Classes

The classes are restricted to the defaults listed. To add more classes to the post content area, the template tag's parameter can be added. For example, to add a unique class to any template file:

The results would be:

Or you can use an array with classes:

Add Classes By Filters

To add a category class to single post pageviews and template files in the post content area for the post class and the entire page in the body HTML class, add the following to the functions.php.

Display Posts Outside of the Loop

For displaying posts outside the Loop or in an alternate Loop, the second parameter to the post_class function can be the post ID. Classes will then be determined from that post.

post_class() 示例