Let’s say you have a post under a subcategory and you want to show only the top level category that is assigned to the post, you can use this function:
function GetTopLevelCategory() {
$category = get_the_category();
$parent = $category[0]->category_parent;
while($parent > 0) {
$idlevel = &get_category($parent);
$cat = $idlevel->cat_ID;
$parent = $idlevel->parent;
}
$name = get_the_category_by_ID($cat);
$link = get_category_link($cat);
print('<a href="'.$link.'">'.$name.'</a>');
}
Tags: wordpress







