Support » Fixing WordPress » Get Next 5 Posts from the Current Post

  • This is deceptively simple… I can’t find an answer that works anywhere else in the support forums. On the single post template, I want to generate 5 more recent posts offset from the current post. I’m making an album navigation, so there are 5 CDs (each is a post called from the album category, using custom meta to display a band name and cover image) at the bottom of the single-post template, each one more recent than the next. I want them to be offset from the post you’re currently viewing, so that when you click the next CD, the page refreshes, the single template displays the one you clicked, and you get the next five CDs, and not the most recent 5 cds.

    I’ve tried:

    1) Playing with get_previous_post() (to attempt to get the next one from the current post). This method ultimately can only get the next or previous post from the current post, but not 4 more.

    2) Using offset. I can’t find a way to get 5 posts offset from the current post, though I can obviously get at least 1. I tried multiple custom wp_queries, but there’s no way to establish a starting point in the query() variable.

    3) I thought I might be able to do the trick with the Recent Posts plugin, but the skip variable in this plugin always skips from the most recent post in the category, never from the current post.

    Any ideas?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Thread Starter Daniel Quinn

    (@djquinn)

    No takers?

    Thread Starter Daniel Quinn

    (@djquinn)

    Okay if it’s dead simple, show me how dumb I am for missing it…

    I think I can help you:

    <?php
    $prevPost = get_previous_post();
    $i = 0;
    $num_prev_posts = 5;
    while ($i < $num_prev_posts) //needs to check if $prevPost exists. while ($i < $num_prev_posts && !empty($prevPost)) doesn't work.
    {
    get_permalink($post->ID); //and other such functions that work on the global $post should now work.
    
    $i++;
    $prevPost = get_previous_post(); // and then there should be a check if $prevPost is empty or not
    }
    ?>

    I used a while loop because there’s a possibility that there aren’t enough previous posts and so the loop should be able to end abruptly. I just don’t know how to check if $prevPost is empty, !empty($prevPost) or $prevPost != '' won’t work. There’s not much documentation for get_previous_post() or get_next_post();

    That’s untested code but I think that tells you the logic in it. I hope that helps somehow.

    Thread Starter Daniel Quinn

    (@djquinn)

    Hey wow, I didn’t even see your reply! I’ll check out your code when I get home and see if it works. Thanks for the help!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Get Next 5 Posts from the Current Post’ is closed to new replies.