Keep the Category Class on all posts in the Category

Hi!

I am trying to differentiate Categories design-wise.

My idea is to color certain elements based on the category of the post.

The main Category index has the category-category-name class. However, this class is lost on posts in those Categories.

Would there be a way to keep those classes on the posts too?

Also, there is an Accent color on each Category settings page, but does it do anything in X/Pro, and/or can that be used somehow?

Thanks!

Hi,

To add category class in your post, you can add the code below in your child theme’s functions.php file

add_filter('body_class','add_category_to_single');
  function add_category_to_single($classes) {
    if (is_single() ) {
      global $post;
      foreach((get_the_category($post->ID)) as $category) {
        // add category slug to the $classes array
        $classes[] = "mycategory-".$category->category_nicename;
      }
    }
    // return the $classes array
    return $classes;
  }

Please note that I added mycategory- prefix to prevent conflict. So the class will be mycategory-category-name

With regards to accent color, can you provide us a screenshot of that setting.

Thanks

Hi! Thanks for the Code!

Sorry about the Accent Color question. I have just realized it is coming from some plugin. Probably BBPress or MemberPress.

Thanks again!

You’re welcome, @Misho. I’d just like to add that there is a category class outputted in the body in the archive page and in the single post, the category classes are outputted in the article element. For more details, please watch this video at https://youtu.be/EcTAMPVDo2c. You would not need a custom code unless the element you’d like to override is directly under the body tag or isn’t covered by the article element in a single post.

Those category classes are outputted in each posts in the blog page by the way. See https://youtu.be/ev0osyNpxjc

Hope that gives you another option.

Oh wow, I could swear that I was doing a search for the class in the Source code.

I have still missed it somehow. :slight_smile:

Thanks for the tip, that’s great!

You’re most welcome!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.