Group list of posts by taxonomy and allow for pagination

I figured it out!

First step, is to sort the posts by taxonomy (so that they’re grouped together).

This will give a list of posts that can be paginated (just like a regular list).

The trick now, is to add a (taxonomy) heading above related posts.

So, for each pass of the loop Im looking at the taxonomy in which the post belongs.
When this changes, I know that the “taxonomy group” has changed and therefore I need to show a heading.

E.g. Using my original example

  • 1 (Taxonomy A)
  • 2 (Taxonomy A)
  • 3 (Taxonomy B)
  • 4 (Taxonomy B)
  • 5 (Taxonomy B)
  • 6 (Taxonomy B)
  • 7 (Taxonomy C)
  • 8 (Taxonomy C)
  • 9 (Taxonomy D)
  • 10 (Taxonomy D)

For the first post, we don’t have a current taxonomy, so display a header

  • A
    • 1 (Taxonomy A)
    • 2 (Taxonomy A)

As we move from posts 2 to 3, the current taxonomy changes, so let’s display a header again

  • B
    • 3 (Taxonomy B)
    • 4 (Taxonomy B)
    • etc.

Here’s the code Im using

<?php if ( $the_query->have_posts() ) : ?>

  <ol>

  <?php $current_taxonomy = ''; while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

  <?php
  $terms = get_the_terms( $post->ID, 'taxonomy_goes_here' );

  if ( $terms && ! is_wp_error( $terms ) ) : 

    $tax_terms = array();

    foreach ( $terms as $term ) {
      $tax_terms[] = $term->name;
    }

    $current_tax_terms = join( ", ", $tax_terms );
  ?>

  <?php endif; ?>

  <?php

    if($current_taxonomy != $current_tax_terms) {
      echo '<li><h2>'.$current_tax_terms.'</h2></li>';
      $current_taxonomy = $current_tax_terms;
    }

  ?>

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

  <?php endwhile; ?>

  </ol>

<?php endif;?>

Leave a Comment