How To Order Custom Post Types by Custom Taxonomy in WordPress

Need: To customize the display order of custom post type entries listed on a page by their custom taxonomy.

Solution: Deployed the following code on a page template in order to loop the custom taxonomies fora custom post type and display the post content.

$categories = get_terms('taxonomy_name_here', 'orderby=count&order=DESC&hide_empty=1');
 foreach( $categories as $category ): 
 ?>
 <h3><?php echo $category->name; // Prints the cat/taxonomy group title ?></h3>
 <?php
 $posts = get_posts(array(
 'post_type' => 'custom_post_type_name_here',
 'taxonomy' => $category->taxonomy,
 'term' => $category->slug,
 'nopaging' => true,
 ));
 foreach($posts as $post): 
 setup_postdata($post); //enables the_title(), the_content(), etc. without specifying a post ID
 ?>

 <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

 <div class="entry-content"> 
 <?php the_content(); ?>
 </div><!-- .entry-content -->

 </div><!-- #post-## --> 
 <?php endforeach; ?>

<?php endforeach; ?>

The string “orderby=count&order=DESC&hide_empty=1” in the first line is used to order the taxonomy labels by count with the taxonomy containing the most entries on top and taxonomies with not posts are hidden from display on the page.

To reuse this code just replace the “taxonomy_name_here” and “custom_post_type_name_here” strings with the applicable values to your WordPress setup.

This code was deployed in WordPress 3.4.1.

  • Made

    that solve my problem

  • Hugo

    i love u <3

  • 10PL8

    Is there anyway to use your solution, but only output the results based on the current author. So basically.
    – Output results for $curauth by a specific cpt
    – Display only the terms that are associated with the $curauth published posts

    I have searched high and low with no avail… Any help of direction would be very much appreciated.

  • This is exactly what I was looking for!… or at least close enough to build on. Thanks!

  • trilok

    thanks. my problem is solved…

  • Dirkjan

    Exactly what I needed. I’m using it to display all products per category in a woocommerce site! Thanks!

  • hard

    can we do it with another custom taxonomy … so for example term, second term, post …

  • Joao

    That’s great! but every post I publish gets duplicated. Does anybody know what’s going on?

  • Matine

    This works perfectly, thank you so much!!

  • Antoinette

    Thanks a lot for this post 🙂

  • Wetcha Chaima

    Make my day!