I’ve been trying to retrieve the next and previous post in one of my Wordpress templates. Please note that I want to get the full post object instead of just the pre-formatted links to the posts.

The problem I face is that whenever I call these functions wrong posts are returned. They are in the same post type, but they are off by like a few ids (say 3/4).

// Get next and previous link
if ( have_posts() ) {
   while ( have_posts() ) {

The first variable dump returns me the correct post object. The second one returns a page that's around 4 IDs (they range from 64 - 60) off...

I tried calling the functions both with and without parameters, it returned false posts in both situations.

Hope someone has an answer.

  • 2
    Can you share your code? Feb 28, 2019 at 17:01
  • Please note that I’m on a single page. My code is get_next_post() for recieving my next post and get_previous_post() for the previous one, as I explained above. It’s litterly these two lines, not more.
    – Jim
    Feb 28, 2019 at 17:16
  • 1
    These functions rely on the global $post to contain the correct post that you are trying to fetch next/prev from, verify that this contains the correct post object. A secondary query can overwrite this value if it's not reset correctly.
    – Milo
    Feb 28, 2019 at 17:31
  • when I var_dump($post) it returns me the correct object
    – Jim
    Feb 28, 2019 at 19:16
  • 1
    Just to be clear: You're aware that IDs are not necessarily consecutive right? The adjacent post to post 12 could easily be post 16, or 100, or 1000, depending on what other content has been added to the site. IDs are shared by revisions, other post types, media, and menu items. So if you add a post, and it gets ID 60, but then you upload 2 images, and make a revision, the next post you add will be 64. These functions are intended to get the next published post in chronological order based on post date. Mar 1, 2019 at 2:47

1 Answer 1


The problem was that Wordpress uses these functions based on post_date ...

I did an import from an old CMS to Wordpress where I just added all posts within a loop. Some of the dates were a few seconds off. This caused the functions to return 'false' posts.

I actually wrote a custom class that handles getNext() and getPrevious() with a combined function called getSiblings() based on post_id.

I actually wrote a class that fully tackles this problem. Check github for the full code. Contribution would be very much appreciated :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.