Get wordpress posts grouped by years and months

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>               
 <ul>
  <?php
   $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE  post_status = 'publish' AND post_type = 'post' ORDER BY post_date ASC");

   foreach($years as $year) : ?>

    <h4><li><a href="<?php echo get_year_link($year ); ?> "><?php echo $year; ?></a>
     <ul>
      <?php $months = $wpdb->get_col("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND YEAR(post_date) = '".$year."' ORDER BY post_date ASC");

      foreach($months as $month) : ?>

       <h4>
        <li>
         <a href="<?php echo get_month_link($year, $month); ?>"><?php echo date( 'F', mktime(0, 0, 0, $month) );?></a>
         <ul>
          <?php  $theids = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND MONTH(post_date)= '".$month."' AND YEAR(post_date) = '".$year."' ORDER BY post_date ASC");

           foreach ($theids as $theid): ?>

            <h4 style= font-style:italic;><li><a href="<?php echo get_permalink($theid->ID); ?>"><?php echo $theid->post_title; ?></a></li></h4>  

           <?php endforeach; ?>

         </ul>                
        </li></h4>

       <?php endforeach;?>

      </ul>
     </li></h4>

    <?php endforeach; ?>

   </ul>
  </div>
</div>

Leave a Reply

Your email address will not be published.