Here’s what I found which I’ll break up into pieces:
for ($i = 1; $i <= 12; $i++) {
$month = date("n", strtotime( date( 'Y-m-01' )." -$i months"));
$year = date("Y", strtotime( date( 'Y-m-01' )." -$i months"));
The for
loop will loop through how many months we want to pull, which in this case is 12. The $month
variable will hold an integer without any leading zeros that we can use to reference the current (inside loop current) month later. I’m using strtotime
to start at 1st day of the current (Real Time) month and count backwards from there. The same thing will happen with $year
$tmpQuery = new WP_Query(array('monthnum' => $month, 'post-type' => 'post'));
We can then use the $month
variable to query all posts in that month. Then we can go into our normal loop.
<?php
for ($i = 1; $i <= 12; $i++) {
$month = date("n", strtotime( date( 'Y-m-01' )." -$i months"));
$year = date("Y", strtotime( date( 'Y-m-01' )." -$i months"));
$tmpQuery = new WP_Query(array('monthnum' => $month, 'year' => $year, 'post-type' => 'post'));
if($tmpQuery->have_posts()) :
?>
<h2><?php echo date("F", mktime(0, 0, 0, $month, 10)); ?> - <?php echo $year; ?></h2>
<ul>
<?php while($tmpQuery->have_posts()) : $tmpQuery->the_post(); ?>
<li><a href="https://wordpress.stackexchange.com/questions/119802/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php else : ?>
<p>No Posts This Month</p>
<?php endif;
// wp_reset_query();
}
?>