Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Wordpress archives page showing all posts in reverse chronological order, sorted by year then month with nested lists.
Template Name: Master Archives Page
<?php get_header(); ?>
<article class="archive-list">
<h2>Blog Archives</h2>
// Timeliness variables
$month = '';
$year = '';
$prevmonth = '';
$prevyear = '';
// We want to treat the latest month and year differently
$latestmonth = '';
$latestyear = '';
// Switches, because we want to do something special at the start of a new month and year
// Default 1 (true)
$newmonth = 1;
$newyear = 1;
// Cycle through all the posts to display the archive
// All right, let's get into the loop
if (have_posts()) : while (have_posts()) : the_post();
// Find the month/year of the current post
$year = mysql2date('Y', $post->post_date);
$month = mysql2date('F', $post->post_date);
// If latest month/year haven't been set yet, we know them to be this month/year
if ($latestyear == '') $latestyear = $year;
if ($latestmonth == '') $latestmonth = $month;
// Check if the year and month have changed
if ($year != $prevyear) :
$prevyear = $year;
$newyear = 1;
// Additional check for same month in different year
if ($month == $prevmonth):
$newmonth = 1;
if ($month != $prevmonth) :
$prevmonth = $month;
$newmonth = 1;
// If it's a new year, let's spit out a year heading
if ($newyear) :
// If the new year isn't the latest year, let's close off the year group
if ($year != $latestyear): ?>
<?php endif; ?>
<h3><?php echo $year; ?></h3>
<ul id="<?php echo $year; ?>" class="year-group">
<?php // Don't reset $newyear yet, because the month calculation depends on it
if ($newmonth) :
// If we're a month in the same year, let's close off the month group
if (!($newyear)): ?>
<?php endif; ?>
<li><h4><?php echo $month; ?></h4>
<ul id="<?php echo $month . $year; ?>" class="month-group">
<?php $newmonth = 0;
// Now set to false if it wasn't already false
if ($newyear): $newyear = 0; endif;
<li><?php echo mysql2date('jS', $post->post_date); ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
endwhile; endif;
<?php get_footer(); ?>

This comment has been minimized.

Copy link

@jatstudio jatstudio commented Nov 15, 2014

This is really nice. I was wondering how to get the number of posts of each month.

All the best.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment