Add parent category class to post_class()

Right way to add class to post container HTML tag is post_class() function, it’s also required by Theme Review Guidelines.

Many people ask on WordPress – Stack Exchange how to echo class depending on parent category, best way to do this is to use post_class filter, so I wrote small chunk of code to this.

Following code is based on Chip Bennett’s clever solution. I changed big part of it, but logic is the same.

What the code above does is simple, it gets array of category objects assigned to the post, then if category has parent it adds class ‘category-parent-{parent-cat-name}’, otherwise category is top-level so we are using it.

Problem: If user adds both parent and its child categories, we’ll get duplicated class output of parent category.

This is small problem I’m working now, any suggestions are welcome.

Published by George

Hello, I'm George Mamadashvili ( aka Mamaduka ), Developer from Tbilisi, Georgia.

Join the Conversation


  1. To handle those duplicate classes…

    if ( ! empty( $cat->parent ) ) {
    $parent_cat = &get_category( $cat->parent );
    $class = 'category-' . sanitize_html_class( $parent_cat->slug, $parent_cat->term_id );
    } else {
    $class = 'category-' . sanitize_html_class( $cat->slug, $cat->term_id );

    if( !in_array( $class, $classes ) ) $classes[] = $class;

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: