Support » Plugins and Hacks » Get ID of latest post

Get ID of latest post

  • I’m working on a theme, and I’m editing single.php. What I’m trying to do is very simple, but so far I’ve found no real solution.

    I’m making use of two neat WordPress functions called previous_post() and next_post() (I realise these are deprecated but as far as I know that’s irrelevant in this particular case). Here’s what it looks like:

    <strong>Previous Post: </strong><?php previous_post('%', '', 'yes'); ?>
    <strong>Next Post: </strong><?php next_post('%', '', 'yes'); ?>

    On all my posts except the most recent one, it shows two links at the bottom, one to the next post, and one to the previous post. The problem is that on the latest post on the blog, it shows Next Post: and then just nothing. Because there is no next post.

    So, the obvious solution would be to wrap that one in an if statement, perhaps something like if ($thispostid != $newestpostid) . But then the problem is, how do I actually get the newest post’s ID?

    I was trying to use query_posts() to make an additional mini-loop on single.php whose sole purpose would be to allow me to put the latest post’s $post->ID into a new variable and then compare it à la the if statement above, but this presents a new difficulty. If I put this loop inside my existing while (have_posts()) it screws up next_post() function, even if next_post() is after this new loop’s endforeach;. Somehow next_post() still looks the post information of the most recent loop.

    So finally I tried putting the mini-loop above the main loop, but this also messed things up.

    Surely there’s a better way to get the ID of the latest post without needing multiple loops in single.php! Help, please.

Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Get ID of latest post’ is closed to new replies.