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

Leave a Reply

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