How do I list posts in a custom post type by taxonomy term?

November 10, 2016

Have you ever wanted to list out posts arranged by a taxonomy term associated with that post? This is something that I recently ran into when trying to create a select drop down list of hospital locations arranged by the taxonomy of location type. For example:

Hospitals
Location Post #1
Location Post #2
Location Post #3

Urgent Care
Location Post #4
Location Post #5
Location Post #6

Clinics
Location Post #7
Location Post #8
Location Post #9

and so on.

Well good news is I found a solution:

$custom_terms = get_terms('custom_taxonomy');

foreach($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'custom_post_type',
        'tax_query' => array(
            array(
                'taxonomy' => 'custom_taxonomy',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );

     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        echo '<h2>'.$custom_term->name.'</h2>';

        while($loop->have_posts()) : $loop->the_post();
            echo '<a href="'.get_permalink().'">'.get_the_title().'</a>';
        endwhile;
     }
}

“We get all the terms of a taxonomy, loop through them, and fire off a title link to each post that belongs to that term.”

Original source: http://wordpress.stackexchange.com/questions/66219/list-all-posts-in-custom-post-type-by-taxonomy

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive