Here is a strip down of something similar I’ve done a while ago.
Here is what the code basically does is:
-
First, it retrieves the date of the first post on the block.
-
Secondly, the current date is retrieved.
-
These two values are fed into a
range()
function to get all years in between -
A
foreach
loop get each year separately and that is returned into a customWP_Query
to retrieve posts in that specific year
What you need to do:
-
Add the relevant HTML mark-up that fits your need
-
Sort posts in the order you want
-
Add extra parameters if necessary to suite your needs
Here is the code:
<?php
$oldest = get_posts( 'post_type=post&post_status=publish&posts_per_page=1&order=ASC' );
$oldest_date = $oldest[0]->post_date;
$first_date = date('Y', strtotime($oldest_date));
$todays_date = date('Y');
$year_range = range($todays_date, $first_date);
foreach ($year_range as $year) {
echo '<h2>' . $year . '</h2>';
$args = array(
'posts_per_page' => -1,
'post_type' => 'post',
'post_status' => 'publish',
'year' => $year,
);
$yearly_posts = new WP_Query($args);
if($yearly_posts->have_posts()) {
echo '<ul>';
while($yearly_posts->have_posts()) {
$yearly_posts->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
}
}
wp_reset_postdata();
?>