Display post_count for yearly archives (in WordPress)?

Posted by Thao on Programmers See other posts from Programmers or by Thao
Published on 2012-09-24T04:40:14Z Indexed on 2012/09/24 9:50 UTC
Read the original article Hit count: 144

Filed under:

I'm using this code (which I sourced online) to display date archives in a WordPress theme. It extracts the month and year info, plus post_count, and displays the $month->post_count as expected.

But how can I also display the total post_count for each year?

<?php
  $year_prev = null;
  $months = $wpdb->get_results( "SELECT DISTINCT MONTH( post_date ) AS month , YEAR( post_date ) AS year,
  COUNT( id ) as post_count FROM $wpdb->posts
  WHERE post_status = 'publish' and post_date <= now( )
  and post_type = 'post'");
    foreach($months as $month) :
      $year_current = $month->year;
      if ($year_current != $year_prev){
      if ($year_prev != null){?>
    </ul>
    <?php } ?>
<h1><?php echo $month->year; ?></h1>
<ul>
  <?php } ?>
   <li><?php echo $month->post_count; ?></li>
      <?php $year_prev = $year_current;
   endforeach; ?>
   </ul>

© Programmers or respective owner

Related posts about Wordpress