treehouse : what would you like to learn today?
Web Design Web Development iOS Development

WP: get_previous_post and get_next_post returning the same post!

  • Hi guys, got a quite frustrating issue!

    I have post navigation to go to the next/prev post on the single of a custom post type. It works perfectly for all posts EXCEPT the very first and the very last item. On these pages there should only be a next OR a prev post, but in my case get_previous_post and get_next_post are returning the same post.

    Here's my code:

    $prevPost = get_previous_post();  
    $nextPost = get_next_post();  
    
     if ($prevPost) {
       echo previous_post_link('<span class="prev-item">%link</span>');  
     }
     if ($nextPost){              
        echo  next_post_link('<span class="next-item">%link</span>');
     }
    

    Any ideas?

  • I have this same problem on the archive pages of my own site. Looking forward to what some smarter people have to say on the subject!

  • Straight from http://codex.wordpress.org/Function_Reference/get_next_post.

    <?php
      $next_post = get_next_post();
      if (!empty( $next_post )): ?>
      <a href="<?php echo get_permalink( $next_post->ID ); ?>"><?php echo $next_post->post_title; ?></a>
    <?php endif; ?>
    

    Or, I am I missing something?

  • Thanks, I did see that in the Codex but unfortunately get_next_post() is returning a post even when there is no 'next' post (and likewise for get_previous_post()), rather than null as per the docs.

    I came across the Ambrosite Next/Previous Post Link Plus http://wordpress.org/extend/plugins/ambrosite-nextprevious-post-link-plus/, which has solved my problem :)

    Cheers