Where should I use post_class()?

It’s actually only important to use it if your theme’s CSS or JS is reliant on something it outputs. It essentially stuffs relevant class names into the HTML tag you put it on based on the current post/category/blah/blah. So, on a single post template this:

<article <?php post_class(); ?>>

might output:

<article class="post post-123 category-3 category-cats status-publish hentry">

You can then use those classes to style things with CSS (or hooks for JavaScript).

When using it with a custom post type, it will also output the post type:

<article class="mycpt type-mycpt post-345 category-3 category-cats status-publish hentry">

It actually always outputs post type. In the first example, post was the post type.

Note that you can also manually pass in custom class names; since the function actually outputs the class attribute itself (vs a list of class names only) this is the only way to get both WP generated classes and custom classes onto an element. So:

<article <?php post_class( 'my-custom-class' ); ?>>

will added my-custom-class to the string of classes output by WordPress.

Codex article: https://codex.wordpress.org/Function_Reference/post_class

EDIT: From the comments “Okay, so post_class() should be used on the single-post-page?”

You can use it on any template. Indeed, it might even be more commonly used on archive type pages. Let’s say you have a blog with three categories of posts: Tutorials, Editorials and Reviews. On your site’s home page you might have a grid with all of those posts listed out in a single large list. With CSS and post_class() you could style each type of entry differently. Say, adding a graduate hat icon on anything with class="category-tutorial", a pencil icon on anything with class="category-editorial" and so on.

On http://ecotrust.org/search/farms I use the post classes on the search results page to let the user know what type of content each result is. We never got around to designing icons for each so it’s simple text inserted with CSS content.

// a mixin that puts the little words in the bottom right corner
.type-identify(@content-type:" ") {
    &:before {
        content: @content-type;
        bottom: 20px;
        color: #cccccc;
        clear: none;
        display: block;
        position: absolute;
        right: 0;
        text-align: right;
        width: 160px;
        .small-info();
    }
    &:hover:before {
        color: #aaaaaa;
    }
}

// then call it based on the post_class() output for different post types, 
// including custom post types
.type-post {
    .type-identify("Blog post");
}
.type-page {
    .type-identify("Page");
}
.type-press_release {
    .type-identify("Press release");
}
.type-portfolio_item {
    .type-identify("Portfolio");
}
.type-project {
    .type-identify("Project");
}

Leave a Comment