I am not a coder, but I usually get by with WordPress by doing my research and find my solution. I can’t find what I need to do this time so I have attempted to crib together some code – what I am attempting to do is, when I am on the Category Archive, I want to add a body class of the category parent. This is what I have tried and it is working apart from I am getting the parents category ID, but I want the slug/nicename:
add_filter('body_class','hw_custom_body_class');
function hw_custom_body_class($classes){
if(is_category()){
$categories = get_the_category();
$category = strtolower($categories[0]->category_parent);
$classes[]='category-'.$category;
return $classes; }}
Use
get_ancestors()
to get the parent terms. Here is an excerpt from my plugin T5 Parent Terms in body_class:This will work with any taxonomy, not just categories.
The only way I got to display the parent category in the category’s archive page was by following this approach: https://yonkov.github.io/post/add-parent-category-to-the-body-class/
Basically, you need to create a class variable and then pass it to the body class: