If you want to get the the top-level parent of a custom taxonomy term? 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.
1 2 3 4 5 6 7 8 9 10 11 | // 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.