Support

Account

Home Forums General Issues Display Taxonomy Hierarchy Reply To: Display Taxonomy Hierarchy

  • Sure, here’s a direct idea that you can use to display the taxonomy hierarchy on your WordPress website:

    You can use the get_ancestors() function in WordPress to retrieve the ancestors of a taxonomy term. This function returns an array of term IDs, which you can then use to display the hierarchy.

    Here’s an example code snippet that you can use:

    <?php
    // Get the current taxonomy term
    $term = get_queried_object();

    // Get the ancestors of the current term
    $ancestors = get_ancestors( $term->term_id, $term->taxonomy );

    // If there are ancestors, display them
    if ( $ancestors ) {
    // Reverse the order of ancestors to display them from parent to child
    $ancestors = array_reverse( $ancestors );

    // Loop through the ancestors and display them
    for each ( $ancestors as $ancestor ) {
    $ancestor_term = get_term( $ancestor, $term->taxonomy );
    echo esc_html( $ancestor_term->name ) . ‘ – ‘;
    }
    }

    // Display the current term
    echo esc_html( $term->name );
    ?>
    This code will retrieve the ancestors of the current taxonomy term and display them with the current term, separated by a dash. You can modify the output as per your requirements.