I have posts under a custom post type which I like to display in a page grouped by Year and Month. In the page template that I create, I managed to separate them by month, but still without grouping at separate levels (they're all same-level, there's just the month name as a break between the groups), like so:
<div class="month"></div>
<div>post title</div>
<div>post title</div>
<div>post title</div>
<div>post title</div>
<div class="month"></div>
<div>post title</div>
<div>post title</div>
<div>post title</div>
<div>post title</div>
<div class="month"></div>
<div>post title</div>
<div>post title</div>
<div>post title</div>
<div>post title</div>
I did that with:
<?php
global $more; $more = false; # some wordpress wtf logic
$posts = get_posts(array(
'post_type' => 'press',
'nopaging' => true,
'orderby' => 'date',
'order' => 'DSC',
'posts_per_page' => 999999,
));
$month = null;
foreach($posts as $post):
setup_postdata($post); //enables the_title() etc. without specifying a post ID
$postMonth = date('FY',strtotime($post->post_date));
if($month!=$postMonth){
echo '<div class="month">'.date('F Y',strtotime($post->post_date)).'</div>';
$month =$postMonth;
} ?>
<div><a href="<?php the_field('url');?>">"<?php the_title();?>"</a></div>
<?php endforeach;?>
What I want to have is something like this:
<div class="year">
<span>2019</span>
<div class="month">
<span>August</span>
<div>post title</div>
<div>post title</div>
</div>
</div>
<div class="year">
<span>2019</span>
<div class="month">
<span>July</span>
<div>post title</div>
<div>post title</div>
</div>
</div>
<div class="year">
<span>2018</span>
<div class="month">
<span>January</span>
<div>post title</div>
<div>post title</div>
</div>
</div>
I tried pretty every solution I could find on StackExchange to no avail. Any ideas?