My previous and next posts are set on an infinite loop so there is always a previous and next post. I.E. for the newest article the "next" post would be go to the oldest post. And if we're viewing the oldest post, the "previous" post would go to the newest post.
I need to pull in the featured images of the next and previous posts to be the background for the pagination navigation.
I've got the images pulling in when there truly is a next or previous post. However, when the infinite loop is necessary, i.e. next being the oldest post, or previous being the newest post, my code breaks down.
My code is below. I believe the issue is that I'm not actually capturing the ID of what I need in $first_id
and $last_id
. I've tried using get_queried_object_id()
$first->post->ID
and various combinations to get the post ID of what is being pulled in since .previous-title
is working correctly.
<div class="post_nav">
<?php if( get_adjacent_post(false, '', true) ) :
$previous_post = get_previous_post(); ?>
<div class="previous-img"><?php echo get_the_post_thumbnail( $previous_post->ID );?></div>
<p class="previous-title"><?php previous_post_link('Previous Story<br> %link','%title');?</p>
<?php else:
$first = new WP_Query('posts_per_page=1&order=DESC'); $first->the_post();
$first_id = $first->ID; ?>
<div class="previous-img"><?php echo get_the_post_thumbnail( $first_id );?></div>
<?php echo '<p class="previous-title"><a href="' . get_permalink() . '">Previous Story<br>' . the_title() . '</a></p>';
wp_reset_query(); ?>
<?php endif; ?>
<?php if( get_adjacent_post(false, '', false) ) :
$next_post = get_next_post(); ?>
<div class="next-img"><?php echo get_the_post_thumbnail( $next_post->ID ); ?></div>
<p class="next-title"><?php next_post_link('Next Story<br> %link','%title');?></p>
<?php else:
$last = new WP_Query('posts_per_page=1&order=ASC'); $last->the_post();
$last_id = $last->ID; ?>
<div class="next-img"><?php echo get_the_post_thumbnail( $last_id );?></div>
<?php echo '<p class="next-title"><a href="' . get_permalink() . '">Next Story<br>' . the_title() . '</a></p>';
wp_reset_query(); ?>
<?php endif; ?>