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[0];
$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.
Dunc -
Worked great, thanks mate!
L'Homo Economicus -
This tip is usefull. It wordked for me. I needed it for the breadcrumb on my blog.
Nick Boldson -
I found this script useful for breadcrumbs in WordPress: http://dimox.net/wordpress-breadcrumbs-without-a-plugin/
elotse -
Great, this was very helpfull for me