Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

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

Olivia Rhye

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

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy