WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Echo list of terms on taxonomy page (3 posts)

  1. Troy Chaplin
    Member
    Posted 2 years ago #

    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.

  2. Patrick Johanneson
    Member
    Posted 2 years ago #

    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";
    }
    
    echo("<ul>\n$list</ul>\n");

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

  3. Troy Chaplin
    Member
    Posted 2 years ago #

    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:

    <?php
    $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>';
    endif;
    ?>

    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]

Topic Closed

This topic has been closed to new replies.

About this Topic