These are functions that I found on the web years ago and have been using ever since. They appear on all my WordPress websites.
Firstly we have a function to get the ID of the parent category of the current category.
function get_parent_category()
{
foreach ((get_the_category()) as $cat)
{
if ($cat->category_parent)
return $cat->category_parent;
else
return $cat->cat_ID;
}
}
Next we have two functions which form one of the most useful functions ever. It will allow you to pass in a category id and it will tell you if the current post or category is contained within that category, either directly or through child/sub categories.
function in_category_or_subcategory_of($cat_id=0)
{
$cats = get_the_category();
if (!count($cats))
return false;
foreach ((array)$cats as $cat)
{
if ($cat->cat_ID == $cat_id)
return true;
if (in_category_dig_parents($cat->category_parent, $cat_id))
return true;
}
return false;
}
function in_category_dig_parents($cat_id, $look_for)
{
if ( !$cat_id )
return false;
if ( $cat_id == $look_for )
return true;
$cat = get_category($cat_id);
return in_category_dig_parents($cat->category_parent, $look_for);
}
To use it, simply call 'in_category_or_subcategory_of' specifying a category id and it will return true or false depending on the category hierarchy.
These functions were not written by myself, and I do not know who did write them. If you know the author, please let me know so I can give credit where credit is due.