The body_class function is nice for adding a bunch of classes to the body tag that have information about what kind of page is currently being displayed. Probably for styling purposes. But for whatever reason, it doesn’t include a class for the current category (or categories) for a single post.
This adds that category “nice” name:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
// add category slug to the $classes array
$classes[] = $category->category_nicename;
}
}
// return the $classes array
return $classes;
}
Good tip! =]
Just be careful that no category conflicts with an existing necessary body class. A better option would be to add a custom
[data-*]
attribute on the<body>
element, so that it’s separate dataI.E.
The great thing about
[data-*]
attributes is that you can still style them with CSS:Great! But how to create this one? Is any ability to do it in functions.php ?
I second that. This would be a very elegant solution. I don’t think it will work inside this filter / function though. You’d have to add_action probably to add an attribute to the body element some how.
That second argument
$class
is throwing an error for me. I removed just that argument and this works perfectly.Ditto!
Ditto
Same here. Thanks very much for this code!
I found the same thing as Kaela. Works fine so long as I the
$class
arg. Thanks very much!Note that you probably don’t want this to run on the Administration interface. Prevent it using is_admin():
Using this on https://snapagency.com and the above suggestion took me a second to figure out what the change was… removing the second $class did the trick and the code looks like this:
I’m working to make the above work. What I’m attempting to do is add the category name as a class to the individual post even if it shows up on the home page, or blog index. This way, I can make styling adjustments to the post layout based on category. – ie. different color text for each category.
For me, the following code is working for single post.
But, I need something like this for ads page
Can somebody help me?
This code seems to only add one class, even if the post is assigned to multiple categories. How could the code be adjusted to add a class for each and every category?
That would be a delicious tweak.
Hello,
It didn’t work for me. The body classes didn’t change at all. I copy and pasted the snippet above in my function.php and nothig else. My theme uses the plugin ACF (advanced custom field) could this be the reason it didn’t work.
thanks for you help
This works for regular post types, but not for custom post types, at least when I try it.
Any idea on how to make it work for custom post types’ categories too?
I’m trying to put a class to my theme post class if it’s from a specific category slug. I don’t to include all Categories..