Skip to content

How To Add Category ID To Body And Post Class In WordPress

Here’s a snippet which comes very handy if you want to add category ID to body and post class in WordPress for customizing your blog posts. After adding this snippet, you can start styling your posts depending on which category it belongs. It’s an amazing tip to change background or color theme for your categories.

Just add following snippet to your current theme’s functions.php file:

function category_id_class($classes) {
     global $post;
          foreach((get_the_category($post->ID)) as $category)
               $classes [] = 'cat-' . $category->cat_ID . '-id';
               
     return $classes;
}

add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');

Leave a Reply

Your email address will not be published. Required fields are marked *