WordPress – Order/Group Posts by Category or Taxonomy

Published by Leave your thoughts

Sometimes, we get requests to create very custom displays of WordPress Posts. Other times we need to display a WordPress custom post type and group it by it’s category or custom taxonomy. Here’s how I do it:

// IN THIS EXAMPLE, WE HAVE POSTS INSIDE THE CUSTOM TAXONOMY CALLED "cities"
// THIS CODE WILL GROUP ALL POSTS BY THEIR CITY

if (have_posts()) : 

  //GET ALL THE TERMS/CATEGORIES WE WANT TO GROUP POSTS BY
  $allcities = get_terms('cities');

  //LOOP THROUGH EACH CATEGORY
  foreach ($allcities as $citygroup) {

    //LOOP THROUGH ALL POSTS OR ENTIRE CUSTOM POST TYPE
    while (have_posts()) : the_post(); 

      //GAB THIS POSTS CATEGORY
      $thiscity = wp_get_post_terms( $post->ID, 'cities');  

      //ONLY DISPLAY POSTS IN THE SELECTED CATEGORY/CITY
      if($citygroup->name == $thiscity[0]->name) {

        //IF THIS IS THE FIRST POST OF THE CATEGORY, DISPLAY THE CATEGORY NAME
      	if($thiscity[0]->name != $lastcity) {
      	   echo '<h2 class="citytitle">' . $citygroup->name . '</h2>';
      	}
      	$lastcity = $thiscity[0]->name;


        [NORMAL POST LOOP]


      } // END IF
    endwhile;
  } //END CATEGORY LOOP
  
endif; // END have_posts

Categorised in: Wordpress, PHP, Webmaster

This post was written by Ashton