How to list posts in a custom post type by taxonomy term

Ashley Wright

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:

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

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

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

and so on.

Well good news is I found a working and pretty simple solution:

$custom_terms = get_terms('custom_taxonomy');

foreach($custom_terms as $custom_term) {
    $args = array('post_type' => 'custom_post_type',
        'tax_query' => 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>';

“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:

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *