Sort Posts by Category

When generating archive pages, it’s sometimes necessary to return all of the Posts (for a given Post Type), sorted by the Category for visitors to sort through easily.

<?php

//get all categories then display all posts in each term

$taxonomy = 'taxonomy';

$term_args = array(
  'orderby' => 'name',
  'order' => 'ASC'
);

$terms = get_terms($taxonomy,$term_args);

if ($terms) {

  foreach( $terms as $term ) {

    $args = array(

      'tax_query' => array(array( 
      'taxonomy' => 'location',
      'field' => 'term_id',
      'terms' => array($term->term_id), // get the post type term id
      )), 
      'post_type' => 'custom_post_type',
      'posts_per_page' => -1
      // 'caller_get_posts'=> 1 DEPRECATED
      );

    $my_query = null;

    $my_query = new WP_Query($args);

    if( $my_query->have_posts() ) {  ?>

      <div class="category section">

     <h3><?php echo $term->name;?></h3>

     <ul>

     <?php

      while ($my_query->have_posts()) : $my_query->the_post(); ?>

        <li>

         <?php the_post_thumbnail('medium'); ?>

         <h2><?php the_title(); ?></h2>

 <?php the_content(); ?>

        </li>

       <?php endwhile; ?>

      </ul>

      </div>

 <?php    }

  }

}

wp_reset_query();  // Restore global post data stomped by the_post(). ?>

Output:

  • Taxonomy
    • Post
    • Post
    • Post
  • Taxonomy
    • Post
    • Post

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.