PHP, Webmaster, Wordpress

WordPress – Order/Group Posts by Category or Taxonomy

Leave a Reply

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.

WordPress category pages don’t have any customization in the normal WordPress admin dashboard, but through the template files, we’re able to customize to our heart’s content. This client had a very unique situation where they had a custom post type with two different custom taxonomies (City and Category). When we load the a category page, they wanted to group all of the posts by city. There are a few ways to program this, but we found this code was reliable and did not require much more resources to run.

WordPress Category Code Example

Here’s how I did 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

This will require some custom coding for this code to work with your posts and your custom taxonomies. Feel free to reach out to us if you need help to program this for your WordPress website.

Leave a Reply

Your email address will not be published.