1

I have two custom taxonomies: 'cities', & 'policy'. I'd like to display all the terms from each taxonomy at the bottom of a post, with links. This is what I would use for a single taxonomy - let's say cities:

echo get_the_term_list( $post->ID, 'cities', '', ' / ', '' );

But I want the list to include terms in cities and terms in policy.

3
  • 1
    There are the term_links-<taxonomy> and the_terms filter hooks, but how about just call the function once for each the taxonomies.. so echo get_the_term_list( $post->ID, 'policy', '', ' / ', '' ); for the policy taxonomy.
    – Sally CJ
    Commented Jul 14, 2021 at 5:42
  • @SallyCJ Thanks. That's what I'm doing now. I need to figure out how to output the divider " / " so that it only appears if both get_the_term_lists return something: <?php echo get_the_term_list( $post->ID, 'cities', '', ' / ', '' ); ?> / <?php echo get_the_term_list( $post->ID, 'policy', '', ' / ', '' ); ?> Commented Jul 14, 2021 at 6:26
  • You can put them in an array, e.g. $lists = [ get_the_term_list( ... ), get_the_term_list( ... ) ];, then join them using your divider: echo implode( ' / ', array_filter( $lists ) );. Alternatively, you can use wp_get_post_terms() to get the terms in your taxonomies, then manually loop through the array items and echo a link for each term. Just remember that, wp_get_post_terms() does not cache the results, so get_the_terms() is preferred when looping over a posts query result.
    – Sally CJ
    Commented Jul 14, 2021 at 9:50

2 Answers 2

2
<?php
wp_get_post_terms($post->ID, array('cities','policy'));

or
wp_get_object_terms($post->ID, array('cities','policy'));
?>
0

I stuck with sally-cj's suggestion of doing two separate queries. My challenge was how to make the separator work. Using the separator between the two lists resulted in a phantom separator if either list (or both) returned nothing. So I ended up storing the results of each query in a variable and joining them:


    $city_terms = get_the_term_list( $post->ID, 'cities', '', ' / ', '' );
    $policy_terms = get_the_term_list( $post->ID, 'policy', '', ' / ', '' );
    echo $city_terms;
    if ($city_terms && $policy_terms) {
        echo ' / ';
    }
    echo $policy_terms;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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