Archived topic
add class from taxonomy terms to body tag of both pages and posts
3 replies · Started by arachno on August 11, 2021
We need to add to the body class the taxonomy terms (both categories and tags) listed in the post and pages.
What we need to achieve is something like this
<body class="category-red category-yellow tag-one tag-two ...."> those classes shall be added to the standard classes that WordPress assigns to the post/page.
We tried many functions but nothing works as expected.
Thanks for your help
Franco
Hi Franco,
This would be a question for WordPress' support team.
It will likely involve this core filter:
https://developer.wordpress.org/reference/functions/body_class/
If they can provide a snippet that works for a Twenty series default theme, the same snippet would work in GP.
Hope this helps.
we tried something about this
//adds new body class for post or page category
add_filter('body_class', 'add_category_class_single');
function add_category_class_single($classes){
global $post;
$category = get_the_category($post->ID);
$slug = $category[0]->slug;
$classes[] = 'category-' . $slug;
return $classes;
}
but it adds a number after the class and we do not need that number. for example we have a page with the following category
"yellow"
and the result in the <body> tag class is:
<body class="category-yellow-3">
maybe there is something in the above function that adds the number -3 but we don't know where is the problem
any help on this?
I'm not sure why the number is added unfortunately.
This isn't something the themes can control.
Please check with WordPress' support team.
Thanks!