Support » Fixing WordPress » Show Top Level Parent Taxonomy

  • Hello,

    I am currently using the following code to show the parent term of the current taxonomy term.

    <?php
    $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
    $parent = get_term($term->parent, get_query_var('taxonomy') );
    echo $parent->name;
     ?>

    I would also like to include the top level parent of the terms.

    For this particular set up I am using zip codes, city and state.

    Taxonomy set up is as follows:

    State
    ->City
    –>Zip Code

    Currently I have it displaying on the page as Zip Code, City

    I would like to display Zip code, City, State

    Any ideas on what additional code will help me accomplish this, I am currently stuck. Thanks in advance!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter WebStyley

    (@webstyley)

    Anyone have any ideas on this? Thanks

    Thread Starter WebStyley

    (@webstyley)

    Here is what I came up with after some research and trial and error for anyone that needs this:

    <?php $term_id = get_queried_object()->term_id; //Get ID of current term
    $ancestors = get_ancestors( $term_id, 'taxonomy' ); // Get a list of ancestors
    $ancestors = array_reverse($ancestors); //Reverse the array to put the top level ancestor first
    $ancestors[0] ? $top_term_id = $ancestors[0] : $top_term_id = $term_id; //Check if there is an ancestor, else use id of current term
    $term = get_term( $top_term_id, 'taxonomy' ); //Get the term
    echo $term->name; // Echo name of top level ancestor
    ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Show Top Level Parent Taxonomy’ is closed to new replies.