WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm having a hard time getting a set of selected terms in a custom taxonomy presented in a specific way.

I have a hierarchical taxonomy 'places' and a post with the tagged terms:

England (x)
  - London (x)
     - Venue1 (x)
France (x)
  - Paris (x)
     - Venue2
  - Berlin (x)
     - Venue3 (x)

I need to print out:

myPostTitle : Venue1 (London - England)
              Paris (France)
              Venue3 (Berlin)

My problem is, that I can't find a function that will return the tagged terms, in a manner that reflects the hierarchical relationships. I need to be able to determine:

  • Which terms are the actual 'venues' (the 'lowest' tagged child in each of the hierarchies)
  • What parents and grandparents of those 'last children' to include.

I'm outside the loop, and would prefer not to run setup_postdata(). I have the post ID.

share|improve this question

I doubt you're going to find a function that created the exact output you're using, so you're probably looking at two nested called to get_terms(). I usually avoid most other taxonomy-related plugins in favor of get terms. Most of the other functions are wrappers for this one.

Here's some psuedo-code for what I'd do:


// Get all the top-level terms i.e. those without a parent
$top_level_terms = get_terms( 'my_taxonomy', array( 'parent' => 0 ) );

foreach( $top_level_terms as $top_term ) {

    // get child terms. use parent for direct descendants or child_of for all descendents
    $child_terms = get_terms( 'my_taxonomy', array( 'child_of' => $top_term->term_id ));

    // list the parent term    
        '<a href="%1$s">%2%s</a> (',
        esc_url( get_term_link( $top_term->term_id ) ),
        esc_attr( $top_term->name )

    // list all the child terms
    foreach ( $child_terms as $child_term ) {
            '<a href="%1$s">%2%s</a>, ',
            esc_url( get_term_link( $child_term->term_id ) ),
            esc_attr( $child_term->name )

    echo ')';


That code's untested and surely needs some additional arguments from you, but hopefully that can get you started.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.