WordPress: Grouping posts by month/year

I have just been trying to work out how to group posts by year when displaying them in WordPress, something that could come in handy for a portfolio or a section on a website which has posts published infrequently. As I couldn’t find a definite solution elsewhere I thought I’d publish it here in case it helps someone else.

The first clue to how to do this came from Dev Lounge, although their solution uses “the_date” function which allows you to group multiple posts from a single day under one date listing.

However if you want to do this for groupings by year you need to apply a bit of simple PHP and variable assigning.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php
 // Assign the year to a variable
 $year = the_date('Y', '', '', FALSE);

 // If your year hasn't been echoed earlier in the loop, echo it now
 if ($year !== $year_check) {
 echo "<h2 class='year'>" . $year . "</h2>";
 }

 // Now that your year has been printed, assign it to the $year_check variable
 $year_check = $year;
?>

<div id="post-<?php the_ID(); ?>">
<!-- post content etc goes hereĀ  -->
</div><!-- end .post-wrap -->
<?php endwhile; ?>
<!-- previous next nav -->
<?php else : ?>
<!-- posts not found info -->
<?php endif; ?>

The same logic should apply to grouping by month – although you might need to tweak the code a little bit!

Comments