WordPress : How to get category ancestor

It's only fair to share...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponEmail this to someone

Here is code I usually use to find ancestor or parent of a category

[php]

function getCategoryAncestor($cat,$index=0){

$parentCatList = get_category_parents($cat,false,’,’);
$parentCatListArray = @split(",",$parentCatList);
$topParentName = $parentCatListArray[$index];
$charReplace = array(" " => "-", "(" => "", ")" => "");
$topParentSlug = strtolower(strtr($topParentName,$charReplace));
$catAncestor[‘ancestor’] = $topParentName;
$catAncestor[‘ancestor_slug’] = $topParentSlug;
return $catAncestor;

}

// How to use :
// if you have this category (by term ID) structure : 1 > 2 > 3
// to get ancestor of a category ID 3

$ancestors = getCategoryAncestor(3);

// to get parent of a category ID 3

$ancestors = getCategoryAncestor(3,1);

[/php]

I know this code is premature, it’s only works when you didn’t modify the category slug. But at least it is working in almost all my projects :p.

 

It's only fair to share...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponEmail this to someone