1

I have a year archive like this:

2010 - - - - - - - - - - - 2011 - - - - - - - - - - - 2012

And first I had the idea that a year with no posts would be just the same page with the text "No posts found". But I got trouble with that since pages with no content redirects to 404. And that made me realise that that actually is the best. It's more SEO friendly.

So I started to thinking how I will solve the pagination situation. And got this idea, if 2010 doesn't have any posts. That year number will be just grey text and not a link. And the last year with posts will be the previous link. Like this:

2009 ... 2010 - - - - - 2011 - - - - - - - - - - - 2012

The question: How do I in fastest way find the last year from a certain year that has posts?

1

You could do a query for a single post made before the currently viewed year. When sorted by date in descending order (the default) the first result will be from the most recent year with posts.

$current_year = get_query_var( 'year' );

$previous_posts = get_posts( array(
    'numberposts' => 1,
    'date_query'  => array(
        'year'    => $current_year,
        'compare' => '<',
    ),
) );

if ( ! empty( $previous_posts ) ) {
    $previous_year = get_the_time( 'Y', $previous_posts[0] );
}

You can do the same to get the next year with posts, but you need to swap the order, otherwise you'll get the year of the latest post:

$next_posts = get_posts( array(
    'numberposts' => 1,
    'order'       => 'ASC',
    'date_query'  => array(
        'year'    => $current_year,
        'compare' => '>',
    ),
) );

if ( ! empty( $next_posts ) ) {
    $next_year = get_the_time( 'Y', $next_posts[0] );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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