Support » Fixing WordPress » Echo list of terms on taxonomy page

  • Resolved Troy Chaplin


    I’m looking for the best way to echo a list of taxonomy terms from terms in a loop if they exist. Let’s see if I can properly explain this.

    I have a loop running on my taxonomy-name.php page that simply lists all custom post types in an unordered list that have been added to one of three terms within that taxonomy.

    Each of those posts also have 2 or 3 other taxonomies registered. What I want to do is echo another unordered list outside of the loop in my sidebar that displays only the terms that each of the posts have been added to for each additional taxonomy.

    I can easily get those additional lists to echo all terms, but some of them that show up should not be there as the items in main list in the loop are not a part of the terms.

    So what I’m looking for is a way to list terms in a taxonomy group, only if they exist based on what each of the main items in the loop have been categorized with.

Viewing 2 replies - 1 through 2 (of 2 total)
  • What about something like this:

    (Note: I haven’t tested this code at all.)

    // assuming your list of custom posts is $custom_posts
    $term_list = array();   // will end up as an array of term IDs
    foreach( $custom_posts as $cp ) {
      $terms = get_the_terms($cp->ID, $your_taxonomy_name);
      foreach( $terms as $t ){
        if( !in_array( $t->term_id, $term_list ) ){
          $term_list[] = $t->term_id;

    Then, to create your list in the sidebar:

    $list = '';
    foreach( $term_list as $term_id ){
      $term = get_term( $term_id, $your_taxonomy_name );
      $list .= "<li>" . $term->name . "</li>\n";

    Or have I completely misunderstood what you’re looking to accomplish?

    Thanks Patrick. Not sure if your example would work as I wanted, while searching for a solution I came across this topic that contained the following code:

    $taxonomy = 'my_taxonomy';
    $terms = get_the_terms( $post->ID , $taxonomy );
    if ( !empty( $terms ) ) :
    echo '<ul>';
    foreach ( $terms as $term ) {
    	$link = get_term_link( $term, $taxonomy );
    	if ( !is_wp_error( $link ) )
    		echo '<li class="' . $term->slug. '"><a href="' . $link . '" rel="tag">' . $term->name . '</a></li>';
    echo '</ul>';

    After a few modifications, and adding some is_tax conditionals, I came up with the following code that worked perfectly:

    [Code moderated as per the Forum Rules. The maximum number of lines of code that you can post in these forums is ten lines. Please use the pastebin]

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Echo list of terms on taxonomy page’ is closed to new replies.