WordPress : Get top level parent category slug
I was trying to get the top level category slug for a post in WordPress today and got a bit baffled about how to go about it.
If anyone else is trying to do it and stumbles across this, here is how:
<?php // get parent category $parentCatList = get_category_parents($cat,false,','); $parentCatListArray = split(",",$parentCatList); $topParentName = $parentCatListArray; $sdacReplace = array(" " => "-", "(" => "", ")" => ""); $topParent = strtolower(strtr($topParentName,$sdacReplace)); ?>
1. get_category_parents() returns the list of parent categories to the category you pass it.
2. We then use split() to create an array of the categories.
3. Then get the first category in the array.
4. Finally we transform the category name to lower case and use a str_replace to get the slug that it would be called by default.