Add Category ID into the body and post class in WordPress

Here’s a little snippet I regularly use to add the ID of the post/page into the body class and post class. It’s really helpful to aid targeting specific things in CSS, add functionality with javascript and to quickly pinpoint the ID of a page without checking through the back-end.

Add this to your themes functions.php file.

// category id in body and post class
function pro_catid_class($classes) {
global $post;
foreach((get_the_category($post->ID)) as $category)
$classes [] = 'cat-' . $category->cat_ID . '-id';
return $classes;
}
add_filter('post_class', 'pro_catid_class');
add_filter('body_class', 'pro_catid_class');

Useful post? Share it

4 comments on “Add Category ID into the body and post class in WordPress

  1. Brilliant! You just saved me about 3 hours of poking around and fiddling with outdated plugins. This worked for my WordPress 4.2.1 theme Evolve.

  2. Hey Phil, thanks so much for posting this! Going to use it to add corner graphics which highlight the category a post belongs – at the moment I’m manually adding them to each featured image.

    How difficult would it be to do something similar based on either an author role (for example editor) or maybe even an author’s username?

    1. I’m assuming you want to add like a badge or something based on the author level to the corner of the image? Something like this maybe?

      [php]
      <div class="post-thumbnail image-<?php the_author_meta(‘user_level’); ?>">
      <?php the_post_thumbnail(‘full’, array( ‘class’ => "img-responsive attachment-post-thumbnail")); ?>
      <div class="single-meta"><?php the_author_meta(‘user_level’); ?></div>
      </div>
      [/php]

      …and some CSS:

      [css]
      .post-thumbnail {
      position: relative;
      }

      .post-thumbnail .single-meta {
      position: absolute;
      bottom:0;
      right:0;
      background: rgba(240,125,27,0.75);
      color: #fff;
      padding: 5px;
      }
      [/css]

      …not tested this but should point you in the right direction.

Leave a Reply

Your email address will not be published.