Quantcast
Viewing all articles
Browse latest Browse all 13

WordPress : How to get category ancestor

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

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);

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.

 

The post WordPress : How to get category ancestor appeared first on MySandbox.


Viewing all articles
Browse latest Browse all 13

Trending Articles