Grouping WordPress Posts by Month

Jul 20 2009 by Andrew Brown

I wanted to be able to group my posts by months in my wordpress template. I couldn’t find a quick copy and paste online so I wrote my own snippet of code to achieve that result. I had to endure writing php. Since I’ve been a Rails Developer I think I’ve gotten lazier or php is archaic.

group_by_posts

<div class="archives">
<?php 
  $months = $wpdb->get_results("SELECT DISTINCT MONTH(post_date) AS month , YEAR(post_date) AS year FROM $wpdb->posts WHERE post_status = 'publish' and post_date <= now( ) and post_type = 'post' GROUP BY month, year ORDER BY post_date DESC");
  $posts = $wpdb->get_results("SELECT id, post_title, MONTH(post_date) AS month , YEAR(post_date) AS year FROM $wpdb->posts WHERE post_status = 'publish' and post_type = 'post' ORDER BY post_date DESC");
  foreach($months as $this_month){ ?>
  <div class="month">
    <h2><?php echo date("F", mktime(0, 0, 0, $this_month->month, 1, $this_month->year)); ?> <?php echo $this_month->year; ?></h2>
    <?php for ($i = 0; $i <= count($posts); $i++){?> 
      <?php if(($this_month->year == $posts[$i]->year)&&($this_month->month == $posts[$i]->month)){?>
      <p><a href="<?php echo get_permalink($posts[$i]->id); ?>"><?php echo $posts[$i]->post_title; ?></a></p>
      <?php } ?>
    <?php } ?>
  </div><!-- month -->
  <?php } ?>  
</div><!-- archives -->

6 Comments to “Grouping WordPress Posts by Month”

tamilsweet

Thanks :-)
I managed to find this and copy & paste for my requirement.

Steve

Hi – thanks for this, it’s been a huge help.

Is there a way of excluding posts from a particular category (or I guess only including posts from a specific category0 ? I’ve played with the code but my skill/experience levels just aren’t up to it.

any help or suggestions would be much appreciated

Steve

Joshua Davis

works great… but can you isolate this filter by category – seems like you can add something to $posts to filter a specific category?

thanks for any help,

Tom

If I wanted to sort by a single category how would I append that functionality to this snippet?

I’ve created an SQL query to get the category ID:

$cat = $wpdb->get_results("SELECT term_id AS category FROM $wpdb->terms WHERE name = 'Bookmarks'");

BUT

I can’t figure out how to test if the posts are sorted under that category.

If I’m being vague, I can offer more detail information.

Andrew Brown

I think you’d have to write a big ugly join to do what you want to do. You’ll need to do some googling, not sure what to do for that.

tboley

Many thanks for this snippet of code! I used it with some modifications in my upcoming theme. With currently 4,700 posts I set a limit for the query. The use of WP_Cache seems to be useful, too.