1

I have a custom taxonomy of Species and a custom post type of Animals. I would like to display them in a tree view like so:

All Animals

  • Fish (taxonomy term)

    • Shark (Custom Post Type)
    • Sun Fish
  • Mammals

    • Monkey
    • Zebra

Each item in the list would be linked to its respective place. So the custom post types link to the animal and the taxonomy terms go to the taxonomy page. I'm aware of ways for WordPress to list categories, but I would also like the posts grouped under each category (custom taxonomy) as well.

2
  • I tried a few plugins and also tried listing the categories and looping through the posts. It seemed a little too involved for what I can do. So I list out the terms, but I'm not sure how to check for posts of that type under the term and list them and move on to the next and repeat.
    – neoian
    Oct 4, 2013 at 15:49
  • Assuming that you're using something like get_terms() to fetch your list of custom categories: As you loop through your categories, you can grab all the posts in that category using get_posts() (see here for an example of getting all posts in a given custom taxonomy).
    – Pat J
    Oct 4, 2013 at 16:25

1 Answer 1

0

Hey @neoian - what you need is a 2 step process.

  1. Loop the categories / terms
  2. Then inside each category / term, query the posts.

.

$terms = get_terms("some_taxonomy");
$count = count($terms);

if ( $count > 0 ){
    foreach ( $terms as $term ) {

    $term_link = get_term_link( $term, 'some_taxonomy' );

        echo '<h4 class="termTitle"><a href="'.$term_link.'">' . $term->name . '</a></h4>';
        $loop = new WP_Query( array( 
            'post_type' => 'some_postype',
            'posts_per_page' => 1000,
            'orderby' => 'date',
            'order' => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => 'some_taxonomy',
                    'field' => 'id',
                    'terms' => $term->term_id
                )
            )
        ));

        // the loop
        echo '<ul>';
        while ($loop->have_posts()) : $loop->the_post();

            // get posts inside term
            $postID     = $loop->post->ID;
            $postTitle  = $loop->post->post_title;

            echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';

        endwhile;
        // reset $post so that the rest of the template is in the original context
        wp_reset_postdata();
        echo '</ul>';
    }
}

remember to:
change "some_taxonomy" to the desired taxonomy and
'some_postype' to your custom post type...

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.