Add the Post Category Name to the Single Post Body Class

Sometimes you want to use your wordpress site for advanced customization such-as assigning different styles to varying category posts.This is a less than a minute task, just copy and paste the following code into the active functions.php file for your theme and save.

// add category nicenames in body and post class
function category_id_class($classes) {
global $post;
foreach((get_the_category($post->ID)) as $category)
$classes[] = $category->category_nicename;
return $classes;
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');

Now, you’ll realize that for each single post’s body class another class has been added. For example if you have a category named “Alphasoft” then all single posts in this category have a class “Alphasoft” in their body class array.

It’s usage is very simple, body.alphasoft identifies such single/category post pages. Go crazy with your css.


Web Geek – Time to get dirty with Cooking Code!
Life without Eternal Focus is an illusion (Life Error 500)

Facebook Twitter LinkedIn Google+ Skype