How To Easily Add Parent Category to the WordPress body class
I had a client that wanted to customize the category archives in such a way that they had different content and layout for all the child categories that belong to a certain parent category. For this, I needed a class name, so i can display it on the frontend and customize each child category’s archive page accordingly. In this tutorial, I will show you how to quickly assign the parent category id as a body class name to any WordPress child category’s archive page. Tested and works on my website.
Add Parent Category Id to Body Class
Here is the code that I used to display the parent category class name on the body tag of each child category. Add this on top of your child theme’s header.php:
<?php
$this_category = get_category($cat);
//If category is parent, list it
if ($this_category->category_parent == 0) {
$this_category->category_parent = $cat;
} else { // If category is not parent, list parent category
$parent_category = get_category($this_category->category_parent);
//get the parent category id
$ParentCatId = $parent_category->cat_ID;
}
$childcategories = array();
$catx = $ParentCatId;
$cats = get_categories('parent='.$catx);
foreach($cats as $cat) {
$childcategories[] = $cat->term_id; } ;
//if it is a child category, add a class with the parent category id
if( is_category( $childcategories ) ) {
$class = 'parent-category-'.$ParentCatId;
}
?>
Now, pass the $class variable as an argument to the body_class function in header.php. Locate the body tag and update it to look like this:
<body <?php body_class($class); ?>>
Now, when you open a child category’s archive page and inspect the page with the developer tools (F11), you should be able to see a body classname that has the id of its parent category. For example, if you want to add styles to the child category that has a parent category with id=2, you can use the following css code:
.parent-category-2{
/* Add your css code here */
}
Happy codng!