Pull in previous and next post featured images int

2019-09-09 23:09发布

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; ?>

1条回答
不美不萌又怎样
2楼-- · 2019-09-09 23:57

You're right, $first and $last are not posts, but queries. You could either use get_the_ID() or grab the ID directly.

$last_id = get_the_ID();

( since you've made it the active loop )

or

$last_id = $last->posts[0]->ID;

which means you wouldn't need to set up the loop for $last, in which case you'd also need to get the permalink and title via functions taking the ID as a parameter. This is a minor optimization, if you get confused here go with the first option.

Also, your next-title and previous-title in the else paths seem to be switched with each other. Or perhaps the entire code blocks are.

查看更多
登录 后发表回答