List of Posts and Categories

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

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.

Related posts

1 comment

  1. 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…

Comments are closed.