Skip to content

Instantly share code, notes, and snippets.

@chocopie
Created September 18, 2013 11:07
Show Gist options
  • Save chocopie/6607641 to your computer and use it in GitHub Desktop.
Save chocopie/6607641 to your computer and use it in GitHub Desktop.

Revisions

  1. chocopie created this gist Sep 18, 2013.
    95 changes: 95 additions & 0 deletions Sorted, nested Wordpress archive
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,95 @@
    <?php
    /*
    Template Name: Master Archives Page
    */
    ?>

    <?php get_header(); ?>

    <article class="archive-list">

    <h2>Blog Archives</h2>

    <?php
    // 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
    query_posts('showposts=-1');

    // 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;
    endif;
    endif;
    if ($month != $prevmonth) :
    $prevmonth = $month;
    $newmonth = 1;
    endif;

    // 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): ?>
    </ul>
    </li>
    </ul>
    <?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
    endif;
    if ($newmonth) :
    // If we're a month in the same year, let's close off the month group
    if (!($newyear)): ?>
    </ul>
    </li>
    <?php endif; ?>
    <li><h4><?php echo $month; ?></h4>
    <ul id="<?php echo $month . $year; ?>" class="month-group">
    <?php $newmonth = 0;
    endif;
    // 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>

    <?php

    endwhile; endif;
    ?>

    </article>

    <?php get_footer(); ?>