0

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
Germany
  - 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.

0

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:

<?php

// 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    
    printf(
        '<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 ) {
        printf(
            '<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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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