Thursday, June 17, 2021

WordPress - How to find parent term of current term

 You have hierarchical categories or custom taxonomy and for SEO reasons or navigation reasons you want to display parent term or the current term.

To get name of the parent term if such is available you can use following code:

Note you have to be on the taxonomy page (archive) for this to work.

function parent_term() { 

$term = get_queried_object();

$parent = "";

if ($term->parent == 0) {

$parent = "";

} else {

$termParent = ($term->parent == 0) ? $term : get_term($term->parent, $term->taxonomy);

$parent = $termParent->name;

}

return $parent;

 

No comments: