get_next_post() not working

I’m using get_next_post() and get_previous_post() in single.php.
But the problem is it’s not displaying Next post on all single posts.
The previous post is displaying on every single page fine but next post is just displaying on first post.
Here is my code:

global $post;
$prevPost = get_previous_post();
$nextPost = get_next_post();
 /* echo '<pre>';
print_r($nextPost);
exit();*/
<?php 
    if($prevPost) {

?>
    <div class="prev">
        <h3><a href="https://wordpress.stackexchange.com/questions/232964/<?php echo get_the_permalink($prevPost); ?>"><?php echo get_the_title($prevPost); ?></a></h3>
        <p><?php echo wp_trim_words( $prevPost->post_content , '40' ); ?></p>     
         <a class="read-more" href="https://wordpress.stackexchange.com/questions/232964/<?php echo get_the_permalink($prevPost); ?>">More...</a>
    </div>
<?php

    }

    if($nextPost) {

    ?>

    <div class="post-next">
        <h4><a href="<?php echo get_the_permalink($nextPost); ?>"><?php echo get_the_title($nextPost); ?></a></h4>
        <p><?php echo wp_trim_words( $nextPost->post_content , '35' ); ?></p>

        <a class="previous" href="<?php echo get_the_permalink($nextPost); ?>">More...</a>
    </div>
<?php

    } // end if
?>

1 Answer
1

Only a guess but you might need

global $post

before your code. According to the Codex docs for the functions you are using the return values are

Null if global $post is not set.

Also you might want to use their suggested logicals:

if (!empty( $prev_post ))

Leave a Comment