At the bottom of single.php, I want to display "card" links to the next and previous posts in chronological order. This is pretty easy thanks to get_next_post()
and get_previous_post
, no problems so far.
However, I want to change that feed when on the most recent post -- that post won't have a next post. Instead of an empty space in my layout, I'd like to display the previous post and its previous post. So the two previous posts instead of just one.
I know how to check if we're on the most recent post, I'm just not sure how to properly call the multiple previous posts. My basic code structure is:
if ( have_posts() ) {
while ( have_posts() ) { the_post();
// output current post here
}
$next = get_next_post();
if( $next ) {
$id = $next->ID;
$url = get_the_permalink( $id );
$title = $next->post_title;
$date = get_the_date( '', $next );
// use these variables to output link to next post
}
$prev = get_previous_post();
if( $prev ) {
$id = $prev->ID;
$url = get_the_permalink( $id );
$title = $prev->post_title;
$date = get_the_date( '', $prev );
// use these variables to output link to previous post
}
// If there's no next post, that means we're on the most recent post.
// To fill the space, let's pull the 2nd previous post.
if( !$next ) {
// Make sure there's a previous post
if( $prev ) {
// Conditions are perfect. Now how do I grab that 2nd previous post??
}
}
}
I'm sure it's some basic query issue. What am I missing?