I’m using get_the_terms to display 2 terms on a post, associated with the taxonomy “location”. The terms are the suburb and the city. The location taxonomy is hierarchical so the suburb is a child of the city.
In the post edit screen a user selects their city, followed by their suburb (which lists the suburbs based on the city they pick). Both are selectable from drop down menus.
My problem is that when the terms are outputted onto the post, it lists them alphabetically, and in some instances the City will be listed first:
Alpha (City), Beta (Suburb)
I need them to reflect their Hierarchy so they are always listed by Suburb first, then city.
Beta (Suburb), Alpha, (City)
Here is my code.
<?php
$terms = get_the_terms ($post->id, 'location');
if ( !is_wp_error($terms)) : ?>
<li id="location">
<?php unset($locations);
foreach ($terms as $term) {
$locations[] = $term->name;
}
$location = join(", ", $locations);
?>
<?php echo $location; ?>
</li>
<?php endif ?>
Would this be better achieved with wp_list_categories somehow? It seems there is an option “hierarchical” but unsure on how to use it so it just grabs the post’s terms and not everything
I managed to hack this together using wp_get_object_terms. The
'orderby' => 'term_id'
was most helpful. It’s probably not the best method, but seems to work fine. Because the child terms (suburbs) are always created after the parent terms (Cities), they will always have a higher ID.I think the easiest way to accomplish this in your case would be to reverse the array.
There are more complicated ways to do this, but I think this should work for your situation.