-1

I want to do a list archive "post by post", but separated by year. Like this:

<h2>2014</h2>
<ul>
Post 4
Post 3
Post 2
Post 1
<ul>
<h2>2013</h2>
<ul>
Post 3
Post 2
Post 1
<ul>

is there a way to do this?

2

1 Answer 1

0

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 custom WP_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();                
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.