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 = 'category';
$param_type = 'category__in';
$term_args=array(
  'orderby' => 'name',
  'order' => 'ASC'
);

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

if ($terms) {

  foreach( $terms as $term ) {

    $args = array(
      "$param_type" => array($term->term_id),
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );

    $my_query = null;

    $my_query = new WP_Query($args);

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

      <div class="category section">

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

     <ul>

     <?php

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

        <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

       <?php

      endwhile;

      ?>

      </ul>

      </div>

 <?php

    }

  }

}

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

?>

Sourced here.

The above snipped contains deprecated code, and is not tailored for usage with Custom Post Types. For something more up-to-date, please refer to the following:

<?php

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

$taxonomy = 'taxonomy';

// $param_type = 'category__in'; no longer in use

$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.