fbpx
How to Add Category Id to WordPress Body and Post Class

How to Add Category Id to WordPress Body and Post Class

This WordPress snippet is very handy if you wish to add the category ID to the body or post-class for ie. targeting CSS styles and such.

Instructions
Add this to your 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');

WordPress Snippet Info

Tested with Wordpress v. NA
Review Status: Needs Review

How to Add Category Id to WordPress Body and Post Class
4.5 (90%) 8 vote[s]
Please report broken snippets.
Report Broken Snippet

Recent Comments