get the top parent category in WordPress
Here’s a cool little scrap of code to get the name of the top parent category in WordPress. This is another one of those things i spent a good deal of time trying to find through a lot of web searching. I finally came across a post somewhere (can’t remember where anymore) which had the solution I was looking for. I’ve just changed some of the wording (for my own benefit) and have posted it here. This will get the top parent category name, no matter how many levels deep in the category heirarchy you might be. To get this up and running, just add the code below to your functions.php file…
<?php
function get_parent_category_name($cat) {
$parentCategoryList = get_category_parents($cat, false, ',');
$parentCategoryListArray = split(',', $parentCatList);
$parentName = $parentCategoryListArray[0];
$stuffToReplace = array(' ' => '-', '(' => '', ')' => '');
$parent = strtolower(strtr($parentName,$stuffToReplace));
return $parent;
}
?>
Then, put this bit in your template where you want to place the top parent category name…
<?php get_parent_category_name($cat); ?>
This function returns the category “slug”.
To return the actual category name, replace the last line in the block of code above with this…
return $parentName;
Have fun…
comments
One Response to “get the top parent category in WordPress”
Leave a Reply









Great solution! However there is a small typo in this function:
$parentCategoryListArray = split(‘,’, $parentCatList);
needs to be
$parentCategoryListArray = split(‘,’, $parentCategoryList);
to function correctly.