I have a country taxonomy with children taxonomies > state & city.

For a given entry for a restaurant in Nantucket, I want it to say “Nantucket, Massachusetts, United States (each linked to those taxonomy pages)”, but the code I have gotten to work (I’m new to PHP) outputs:

Massachusetts, Nantucket, United States

$terms_as_text = get_the_term_list( $post->ID, 'country', '', ', ', '' ) ; 
echo strip_tags($terms_as_text);

How to I get this to order by the reverse hierarchical order of the taxonomy > City, State, Country?

Any suggestions?

2 Answers
2

To expand on my comment above, you would replace your code with something like this:

print_taxonomy_ranks( get_the_terms( $post->ID, 'post_tags' ) );

and in your function print_taxonomy_ranks you’d replace the echo statement with your preferred output.

function print_taxonomy_ranks( $terms ) {
// if terms is not array or its empty don't proceed
if ( ! is_array( $terms ) || empty( $terms ) ) {
    return false;
}

foreach ( $terms as $term ) {
    // if the term have a parent, set the child term as attribute in parent term
    if ( $term->parent != 0 )  {
        $terms[$term->parent]->child = $term;   
    } else {
        // record the parent term
        $parent = $term;
    }
}

echo "Order: $parent->name, Family: {$parent->child->name}, Sub-Family: {$parent->child->child->name}";
}

Extracted from this answer

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *