As I was implementing my new site, I couldn’t quite get my archives page to display the way I intended. What I wanted was a list of months grouped by year. Wordpress has a function built in called wp_get_archives that will display your archives by month, but this can generate a very long list, and it does not group by year like I wanted. I also found this example, which is closer to what I wanted, but still not quite right. I also looked at a few plugins, but I ultimately decided to just write the code myself.

If you decide to implement this code, you will likely want to put the following code into your archives page (probably archives.php) in your theme directory. This will get you a monthly archive like the one on my archives page.

  1. <?php
  2.     $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC");
  3.     foreach($years as $year) :
  4.         echo '<h4>' . $year . '</h4>';
  5.         echo '<ul>';
  6.         $months = $wpdb->get_col("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND YEAR(post_date) = '" . $year . "' AND post_type = 'post' ORDER BY post_date DESC");
  7.         foreach($months as $month) :
  8.             $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND MONTH(post_date) = '" . $month . "' AND YEAR(post_date) = '" . $year . "' AND post_type = 'post'");
  9.             echo '<li><a href="' . get_month_link($year, $month) . '">' . date("F", mktime(0, 0, 0, $month, 1, $year)) . '</a> (' . $count . ')</li>';
  10.         endforeach;
  11.         echo '</ul>';
  12.     endforeach;
  13. ?>