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>';
    if($prevPost) {

    <div class="prev">
        <h3><a href="<?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="<?php echo get_the_permalink($prevPost); ?>">More...</a>


    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>

    } // end if
  • Please format your code properly! – sarahcoding Jul 22 '16 at 17:36
  • Hi Dan9 check now. – DaNish Ali Jul 22 '16 at 17:50
  • Underlying logic is quite involved and runs raw SQL. Hard to guess why would it be failing. – Rarst Jul 22 '16 at 17:59

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 ))
  • Thanks for your suggestions but i already global $post; on the top of file and i also tried this if (!empty( $prev_post )) but not working :( . Its showing the next post on just first post. – DaNish Ali Jul 22 '16 at 18:07
  • I would do more debugging then a print_r; do something like a var_dump($prevPost) so you can see the full post array data being returned. – cogdog Jul 22 '16 at 18:14
  • i already checked by print_r($nextPost) but it returns nothing. and print_r($prevPost) returns the post object. – DaNish Ali Jul 22 '16 at 18:16
  • That's why I suggest using var_dump to print the entire array, you can often debug if you know what info Wordpress is passing through the array. Seeing a post object just tells you it does or does not exist. – cogdog Jul 22 '16 at 21:07

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.