WordPress Tricks: How to add the name of parent category to the body class of a child category archive page

Here is the snippet of code I use to add a specific body class to the child category archive pages on a WordPress site. Paste this into the header.php file of your site’s theme:

<?php $this_category = get_category($cat);
if ($this_category->category_parent == 0) {
$this_category->category_parent = $cat;
} else {
$parent_category = get_category($this_category->category_parent);
$ParentCatId = $parent_category->cat_ID;
$ParentCatName = $parent_category->slug;
}
$childcategories = array();
$catx = $ParentCatId;
$cats = get_categories('parent='.$catx);
foreach($cats as $cat) {
$childcategories[] = $cat->term_id; } ;
if( is_category( $childcategories ) ) {
$class = 'child-category-of-'.$ParentCatName;
}
?> 

Next, make sure the body tag in the header.php file looks like this:

<body <?php body_class($class); ?>>

What this code will do is add the class “child-category-of-cooking-tips” to any archive page for subcategories of the category Cooking Tips.

Please let me know if you have any trouble implementing this into your site or if you are looking for customizations to this code.