wp_get_object_terms – How can I order the resulting array by hierarchy?

I’m returning a custom hierarchal taxonomy via wp_get_object_terms.

The trouble is that the results are being ordered by name or count, neither of which are proving reliable. (I’m using a custom taxonomy for “Location” – City, State, Country – sometimes the State appears before the City)

Read More

Is there a way I can order the resulting array by the custom taxonomy hierarchy?

Is there, perhaps, another way I should be looking at this?

Related posts

Leave a Reply

2 comments

  1. Just a rough sketch to get your idea:

    • countries (hierarchical taxonomy)
      • France (country – sub taxonomy)
        • Champagne (state – sub sub taxonomy)
          • Le Mans (city – term)
          • Angers (city – term)
          • Nantes (city – term)

    And you want to order:

    $query_results = query( 'country' => 'france', 'orderby' => 'state city', 'order' => 'ASC' );
    

    Did i get this right? If not, feel free to edit my answer or update your Q.

  2. You could use wp_list_categories to sort out the hierarchy, it started supporting taxonomies as of 3.0.

    You can see an example of using a custom taxonomy with wp_list_categories on the codex page for the function.

    You’d just need to pass in the term ids from your wp_get_object_terms call to the wp_list_categories include arg, eg.

    wp_list_categories( array( 'include' => $your_array_of_ids ) );
    

    It should then list out the terms of your custom taxonomy in a hierarchal format, though it may not appear so if your theme isn’t padding list elements(so be sure to apply appropriate styling if the results aren’t showing in a hierarchal form).