Display all months with posts and inside each month show the 5 latest posts

I need to display all the months that have active posts, and inside each month I need to display at least 5 posts that are tied to each month.. the HTML will look like this:

News items

Read More
<h6>May</h6>
<ul>
    <li><a href="#">Souvlaki ignitus carborundum</a></li>
    <li><a href="#">Defacto lingo est igpay atinlay</a></li>
    <li><a href="#">Quote meon an estimate</a></li>
    <li><a href="#">Souvlaki ignitus carborundum</a></li>
    <li><a href="#">Defacto lingo est igpay atinlay</a></li>
    <li><a href="#">Quote meon an estimate</a></li>
</ul>
<h6>April:</h6>
<ul>
    <li><a href="#">Sic tempus fugit esperanto hiccup</a></li>
    <li><a href="#">Epsum factorial non deposit</a></li>
</ul>

Not sure how I can go about this or what function to use.. any help/direction would be appreciated.

Related posts

Leave a Reply

2 comments

  1. one possibility is to run all posts through the loop and only output the month once per new month:

    <?php       
    $counter = 0;
    $ref_month = '';
    $monthly = new WP_Query(array('posts_per_page' => -1));
    if( $monthly->have_posts() ) : while( $monthly->have_posts() ) : $monthly->the_post();
    
        if( get_the_date('mY') != $ref_month ) { 
            if( $ref_month ) echo "n".'</ul>';
            echo "n".'<h6>'.get_the_date('F').'</h6>';
            echo "n".'<ul>';
            $ref_month = get_the_date('mY');
            $counter = 0;
        }
    
    if( $counter++ < 5 ) echo "n".'   <li><a href='.get_permalink($post->ID).'>'.get_the_title($post->ID).'</a></li>';
    
    endwhile; 
    echo "n".'</ul>';
    endif; 
    ?>
    
  2. Here’s a more readable version of the solution provided by Michael

    <?php       
    $posts = new WP_Query(array('posts_per_page' => -1));
    if ($posts->have_posts()): ?>
    <ul id="archives">
        <?php 
        $prev_month = '';
        while ($posts->have_posts()): $posts->the_post();
        if (get_the_date('F Y') != $prev_month): 
            $prev_month = get_the_date('F Y'); ?>
        <li class="month"><?= $prev_month; ?></li>
        <?php endif; ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; ?>
    </ul>
    <?php endif; ?>