Navnish Bhardwaj
Navnish Bhardwaj

Reputation: 1718

loop to display taxonomy terms and description

So I am attempting to build the first page in my navigation heirarchy to choose product categories.

I have a custom taxonomy called collections. I would like to create a page that loops through all terms in the collections taxonomy and displays the Term +link and description.

I created a file called taxonomy-collections.php and put the following code in. But it is not doing the trick.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

$terms = get_terms( 'collections' );

echo '<ul>';

foreach ( $terms as $term ) {

    // The $term is an object, so we don't need to specify the $taxonomy.
    $term_link = get_term_link( $term );

    // If there was an error, continue to the next term.
    if ( is_wp_error( $term_link ) ) {
        continue;
    }

    // We successfully got a link. Print it out.
    echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a></li>';
    echo  term_description($post->ID,$term);

    }

echo '</ul>';

?>

<?php endwhile; else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

This is almost straight from the codex so I'm guessing I am missing something.

currently the code has each term displayed as a list, but I do want to change it to a grid format if someone could help with that too.

So each term and description will be wrapped in a div and right aligned with the next.

Thanks

Upvotes: 1

Views: 3286

Answers (1)

Nico Martin
Nico Martin

Reputation: 1278

Like this?

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

$terms = get_terms( 'collections' );

foreach ( $terms as $term ) {

  // The $term is an object, so we don't need to specify the $taxonomy.
  $term_link = get_term_link( $term );

  // If there was an error, continue to the next term.
  if ( is_wp_error( $term_link ) ) {
    continue;
  }

  // We successfully got a link. Print it out.
  echo '<div><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a>';
  echo  term_description($post->ID,$term).'</div>';

}

?>

<?php endwhile; else : ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Upvotes: 1

Related Questions