Forums

Get Previous Post ID? (7 posts)

  1. odecom5
    Member
    Posted 5 years ago #

    Hey guys. I'm setting up a custom blog, and on the index page, I want users to be able to click to go to the next post down, so they don't have to scroll.

    The best way that I can think to do this is to link it to the previous post id (rather than permalink to the previous post). I know how to get the current post ID, but I'm at a loss as to how to get the ID for the previous post. Is this going to require a custom function? i've done a lot of searching but have come up with nothing so far.

    Thanks for your help!

    edit.
    for example, each div is id'ed "post-53" or whatever number the current id post is. I want a link that will go to "#post-52" which goes to the div for post-52.

  2. odecom5
    Member
    Posted 5 years ago #

    bump. any help for this? thanks.

  3. odecom5
    Member
    Posted 5 years ago #

    anyone? :(

  4. odecom5
    Member
    Posted 5 years ago #

    one more time to the top... i hope somebody can help me here. this function is very important to the site

  5. Samuel Wood (Otto)
    Tech Ninja
    Posted 5 years ago #

    The ID for the next post can be retreived like this:

    function get_next_post_id() {
    global $wp_query;
    if ($wp_query->$current_post == $wp_query->$post_count) return 0;
    $next_post = $wp_query->posts[$wp_query->current_post + 1];
    return $next_post->ID;
    }

    Stick that function in the theme's functions.php file. Then just call get_next_post_id() to get the next ID in the posts loop. Like so:
    <a href="#post-<?php echo get_next_post_id(); ?>" />

    It should return zero on the last post though, so you might want to check for that condition.

  6. odecom5
    Member
    Posted 5 years ago #

    thanks for your reply! i'll try it out tonight. Can I also do the same thing for the previous post?

  7. queenvictoria
    Member
    Posted 5 years ago #

    Thanks Otto42 for that code.
    Just a quick correct to Otto42's code. Note the removal of the $ before post_count and current_post on line 3.

    function get_next_post_id() {
    global $wp_query;
    if ($wp_query->current_post == $wp_query->post_count) return 0;
    $next_post = $wp_query->posts[$wp_query->current_post + 1];
    return $next_post->ID;
    }

    And yes, the get_previous_post_id() function would have current_post - 1 on line 4.

Topic Closed

This topic has been closed to new replies.

About this Topic