Archive page with year/months – WordPress Development Stack Exchange


I need to create a date archive that would look like this:

2020 2019 2018 2017 2016
JANUARY FEBRUARY MARCH JUNE

Initially it shows the posts belonging to the most recent month/year but you can navigate through the archive and check posts like: i.e /2020 or /2020/08 or /2019/02 and so on.

I managed to show a list with all years and months inside them, but it’s not what I’m trying to achieve.

Any help is much appreciated.

<?php
                    global $wpdb;
                    $limit = 0;
                    $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' GROUP BY month , year ORDER BY post_date DESC" );
                    foreach( $months as $month ) :
                        $year_current = $month->year;
                        if ( $year_current != $year_prev ) {
                                if ( $year_prev != null ) { ?>
                                <?php } ?>
                                <ul class="date-year">
                        <li><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/"><?php echo $month->year; ?></a></li>
                                </ul>
                        <?php } ?>
                                <ul class="date-month">
                        <li><a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date("m", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>"><span class="archive-month"><?php echo date_i18n("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span></a></li>
                                </ul>
                    <?php
                    endforeach;
                    ?>