WordPress – How to show only years and months that have posts in archive list

I have this archive list that shows me posts by year and month. But it shows years and months that don’t have posts. How can I do to show only months and years that actually have posts? Thank you.

<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM    $wpdb->posts WHERE  post_status = 'publish' ORDER BY post_date DESC"); ?>

<?php foreach($years as $year) : ?>
<span class="anni"><?php echo $year; ?></span>
        <ul style="list-style-type:none;"> 
        <?php $months = $wpdb->get_col("SELECT DISTINCT MONTH(post_date) FROM $wpdb->posts WHERE post_status = 'publish' AND YEAR(post_date) = '".$year."' ORDER BY post_date DESC"); ?>

        <?php foreach($months as $month) : ?>

        <li><h3 class="mesi"><?php echo date( 'F', mktime(0, 0, 0, $month) );?></h3>
            <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 DESC"); ?>

                <?php foreach ($theids as $theid): ?>
            <li class="archivelist">


                    <div style="width:150px;height:170px;float:left;margin:10px;">
            <a href="<?php bloginfo('url'); ?>?p=<?php echo $theid->ID; ?>">

            <?php if (strlen($theid->post_title) > 15) :?>
                <?php echo substr($theid->post_title, 0, 15) . '...'; ?>
            <?php else : ?>
                <?php echo $theid->post_title; ?>
            <?php endif; ?>

            <?php if (has_post_thumbnail($theid->ID) ) : ?>
                    <?php echo get_the_post_thumbnail( $theid->ID, 'thumbnail' ); ?>
            <?php else : ?>
                <?php echo '<img style="width:150px;" src="wp-content/themes/twentythirteen-child/images/noimg.jpg"/>' ;?>
            <?php endif; ?>
                </a>

            </div>
            </li>
                <?php endforeach; ?>

            </ul>   <br style="clear:left;"> 

        </li>

        <?php endforeach; ?>

        </ul>


    <?php endforeach; ?>

Related posts

Leave a Reply

2 comments

  1. Apparently there are posts with other type than ‘post’ in months, that shouldn’t be displayed.

    Try to include

    AND post_type = 'post'
    

    into your WHERE clause in queries used for choosing years and months.

  2. This is how I do it:

     SELECT JAL.year, JAL.month, COUNT(JAL.ID) as `posts` FROM (" .
            "SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`,ID " .
            "FROM {$wpdb->posts} {$join} {$where}" .
     ") JAL GROUP BY JAL.year,JAL.month ORDER BY JAL.year,JAL.month DESC
    

    You do a select of all posts then extract its years an months, then group them by year and month.