Wordpress - Get the the top-level parent of a custom taxonomy term
Thanks to Ivaylo for this code, which was based on Bainternet's answer.
The first function below, get_term_top_most_parent
, accepts a term and taxonomy and returns the the term's top-level parent (or the term itself, if it's parentless); the second function (get_top_parents
) works in the loop, and, given a taxonomy, returns an HTML list of the top-level parents of a post's terms.
// Determine the top-most parent of a term
function get_term_top_most_parent( $term, $taxonomy ) {
// Start from the current term
$parent = get_term( $term, $taxonomy );
// Climb up the hierarchy until we reach a term with parent = '0'
while ( $parent->parent != '0' ) {
$term_id = $parent->parent;
$parent = get_term( $term_id, $taxonomy);
}
return $parent;
}
Once you have the function above, you can loop over the results returned by wp_get_object_terms
and display each term's top parent:
function get_top_parents( $taxonomy ) {
// get terms for current post
$terms = wp_get_object_terms( get_the_ID(), $taxonomy );
$top_parent_terms = array();
foreach ( $terms as $term ) {
//get top level parent
$top_parent = get_term_top_most_parent( $term, $taxonomy );
//check if you have it in your array to only add it once
if ( !in_array( $top_parent, $top_parent_terms ) ) {
$top_parent_terms[] = $top_parent;
}
}
// build output (the HTML is up to you)
$output = '<ul>';
foreach ( $top_parent_terms as $term ) {
//Add every term
$output .= '<li><a href="'. get_term_link( $term ) . '">' . $term->name . '</a></li>';
}
$output .= '</ul>';
return $output;
}
Since 3.1.0, get_ancestors()
is available. It returns an array of ancestors from lowest to highest in the hierarchy.
Here is a simple function that will get you the top most parent term of any given term:
function get_term_top_most_parent( $term_id, $taxonomy ) {
$parent = get_term_by( 'id', $term_id, $taxonomy );
while ( $parent->parent != 0 ){
$parent = get_term_by( 'id', $parent->parent, $taxonomy );
}
return $parent;
}
Once you have this function you can just loop over the results returned by wp_get_object_terms
:
$terms = wp_get_object_terms( $post->ID, 'taxonomy' );
$top_parent_terms = array();
foreach ( $terms as $term ) {
//Get top level parent
$top_parent = get_term_top_most_parent( $term->ID, 'taxomony' );
//Check if you have it in your array to only add it once
if ( !in_array( $top_parent->ID, $top_parent_terms ) ) {
$top_parent_terms[] = $top_parent;
}
}