Archive Page for Wordpress Blogs – May 13, 2013

A customer wanted a "site index" page for their Wordpress site, which in blog terms means an "archive" page.  You can use the wp_get_archives() function, but that doesn't give you much in the way of customization.  I thought about using the "format=custom" parameter, and try to parse the information afterwards, but that seemed like a pain, so I threw away that function call, in favor of calling get_posts, and then doing all of the setup myself.

Here is what I ended up with (note, I'm skipping the template specific stuff, you'll want to include a header, and an appropriate div, and your sidebar(s), etc. There are many sites on the internet that will show you how to create a generic archives.php template)

$archive_posts = get_posts(array('category' => 'blog', 'numberposts' => -1));
$current_year=$current_month='';
foreach($archive_posts as $archive_post){
        $post_year = mysql2date("Y", $archive_post->post_date);
        if($current_year != $post_year){
                if($current_year == ''){
                        print '<ul>'; // first year
                }
                else{
                        print '</ul></li></ul></li>'; // closeout previous month and year
                }
               
                $current_year = $post_year;
                $current_month = '';
                print '<li>'.$current_year.'<ul>';
        }
       
        $post_month = mysql2date("F", $archive_post->post_date);
        if($current_month != $post_month){
                if($current_month != '')
                        print '</ul></li>';
                $current_month = $post_month;
                print '<li>'.$current_month.'<ul>';
        }
       
        print '<li><a href="'.get_permalink($archive_post->ID).'">'.$archive_post->post_title.'</a></li>';
}
print '</ul></li></ul></li></ul>';

And that's it.  Put that code in an archives.php template file, and assign it to the page you want to display the archives, and you'll get a site index page that is ordered by month and year, and shows the post titles for each post.

So, it will look something like the following.  You can style it (maybe remove the bullet points?) with regular CSS rules for unordered lists.

  • 2013
    • December
      • Post 3
      • Post 2
      • Post 1
    • November
      • Post 3
      • Post 2
      • Post 1
    • May
      • Post 3
      • Post 2
      • Post 1
  • 2012
    • December
      • Post 3
      • Post 2
      • Post 1
    • November
      • Post 3
      • Post 2
      • Post 1
    • May
      • Post 3
      • Post 2
      • Post 1
  • ...