一种解决方案是增加缺失的月份。您必须检查是否存在一年中的所有月份。如果不是,则将该月添加为post_count
零
<?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\'
GROUP BY month , year
ORDER BY post_date DESC");
function month_exist($month, $year, $objects){
foreach($objects as $object){
if( ($object->month == $month) && ($object->year == $year) )
return true;
}
return false;
}
$all_month = range(1,12);
$new_array = $months;
$i = 0;
foreach($months as $month){
$year_current = $month->year;
if( $year_current != $year_prev ){
foreach( $all_month as $current_month ){
if( !month_exist($current_month, $month->year, $months)){
$value = new StdClass();
$value->month = $current_month;
$value->year = $month->year;
$value->post_count = 0;
array_splice($new_array, $i*12+($current_month-1), 0, array($value));
}
}
$i++;
}
$year_prev = $month->year;
}
$months = $new_array;
$year_prev = null;
foreach($months as $month) :
$year_current = $month->year;
if ($year_current != $year_prev){
if ($year_prev != null){?>
</ul>
<?php } ?>
<h3><?php echo $month->year; ?></h3>
<ul class="archive-list">
<?php } ?>
<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("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span>
</a>
</li>
<?php $year_prev = $year_current;
endforeach; ?>
</ul>