In wordpress, Im trying to loop through every year archives, displaying a list of every mouth per year.
The html output should look like this:
//year output
<ul>
<li>
2020
//month output
<ul>
<li>month1</li>
<li>month2</li>
<li>month3</li>
</ul>
</li>
<li>
2019
<ul>
<li>month1</li>
<li>month2</li>
<li>month3</li>
</ul>
</li>
</ul>
But the problem is, its repeating all months of every year for each year.
Here is the problem php, I dont know how to write the loop correctly:
<?php
foreach($months as $month) : $year_current = $month->year;
?>
<li class='list-group-item month'>
<a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date("m", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>/?post_type=<?php echo $current_post_type ?>">
<span class="archive-month"><?php echo date_i18n("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span>
</a>
</li>
<?php endforeach;?>
Here is the full php:
<aside class="cms-sidebar">
<h3 class="cms-sidebar-ttl js-toggle-menu-01">過去の記事</h3>
<div class="side-element">
<ul class="side-list">
<!-- year -->
<?php
global $wpdb;
$limit = 0;
$year_prev = null;
$current_post_type = get_post_type();
$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 = '$current_post_type' GROUP BY month , year ORDER BY post_date DESC");
foreach($months as $month) : $year_current = $month->year;
if ($year_current != $year_prev){
?>
<li class="side-item">
<h3 class="side-sub-element-ttl js-toggle-menu-02">
<?php
$args = array(
'post_type' => $current_post_type,
'date_query' => array(
'year' => $month->year
)
);
$year_query = new WP_Query($args);
?>
<?php echo $month->year; ?>年
</h3>
<div class="js-toggle-content">
<!-- months -->
<ul class="side-sub-list flex-row">
<?php
foreach($months as $month) : $year_current = $month->year;
?>
<li class='list-group-item month'>
<a href="<?php bloginfo('url') ?>/<?php echo $month->year; ?>/<?php echo date("m", mktime(0, 0, 0, $month->month, 1, $month->year)) ?>/?post_type=<?php echo $current_post_type ?>">
<span class="archive-month"><?php echo date_i18n("F", mktime(0, 0, 0, $month->month, 1, $month->year)) ?></span>
</a>
</li>
<?php endforeach;?>
</ul>
<!-- end of months -->
</div>
</li>
<?php } ?>
<?php
$year_prev = $year_current;
endforeach;
?>
<!-- end of year -->
</ul>
</div>
</aside>