Tag: get_cateogry_parents

Get Top Parent Category (WordPress)

There are many times when you need to show or get the top most (root) parent category in WordPress – regardless of how many subcategories you might be deep. I have used this logic for page navigation (highlight the top parent tab) – as well as within some custom loops/sidebar code.

They way to do this:

// get parent category slug
$parentCatList = get_category_parents($cat,false,',');
$parentCatListArray = split(",",$parentCatList);
$topParentName = $parentCatListArray[0];
$sdacReplace = array(" " => "-", "(" => "", ")" => "");
$topParent = strtolower(strtr($topParentName,$sdacReplace));	

To test this you can simply put it in your header and echo out $topParent and you will see the “slug” of the category.
If you want to see the category name and not necessarily the slug – you can simply echo $topParentName.