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(',', $parentCategoryList);
    $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…

6 thoughts on “get the top parent category in WordPress

  1. Great solution! However there is a small typo in this function:

    $parentCategoryListArray = split(‘,’, $parentCatList);

    needs to be

    $parentCategoryListArray = split(‘,’, $parentCategoryList);

    to function correctly.

  2. Hello,
    nice function, was searching for it, but
    it seem this function dont works in some cases : accent and ponctuation, the name of one my cat was : “who are we ?” and i got “who-are-we-?”,
    and an other cat was : “activité”, same issue 🙁
    have yu some tips to go further ? , i realy need that function, and dont understand half of it,

    ty ofr yur work

Leave a Reply

Your email address will not be published. Required fields are marked *