1

I'm looking for a succinct method of making get_next_post()
double back to the beginning once it hits the last post.
Currently, it stops once it hits the final post.

Here are a few lines of code from the codex
for context that are similar to what I'm using:

    <?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; ?>

http://codex.wordpress.org/Function_Reference/get_next_post

Thanks in advance for your suggestions.

1

get_next_post doesn't really know what the "beginning" is. get_next_post uses get_adjacent_posts. If you look at the source, you can see that that function runs its own query to determine the next (or previous) post relative to the current post. It doesn't loop through a list.

To get the "first" post, you will need to run a new query based on whatever parameters that you decide meet the condition of returning the first post. Something like this:

while (have_posts()) {
  the_post();
  the_title();
  $next_post = get_next_post();
  if (empty($next_post)) {
    echo 'empty'; 
    $args = array(
      'posts_per_page' => 1,
    );
    $first = new WP_Query($args);
    var_dump($first->post);
  }
  echo '<br>';
}

Also, "next" and "previous" are relative to sort order with "next" meaning closest newer post. In an ordinary default archive Loop, the first post in the list will not have a "next" post. I suspect you actually want to be using previous_post_link but that is a guess.

| improve this answer | |
  • Thanks @s_ha_dum This isn't quite what I'm looking for but it's close. Using var_dump($first->post) helped. Right now, I'm using <?php echo get_permalink( get_post(1) ); ?> to get a link to the first post by id. Is there a succinct method of acquiring the first post's ID without using a static number? – Wilhelm Jan 26 '14 at 20:10
  • $first->post->ID is the post ID, and you can pass get_permalink an ID or a post object. You don't need to run get_post and don't really have to specify the ID if you pass a post object. Since $first->post is a post object, all you need is get_permalink($first->post)). Is that what you are asking? – s_ha_dum Jan 26 '14 at 21:39
  • I tried get_permalink( $first->post ) as well as get_permalink( $first->post->ID ) but to no avail. Only referencing the first post's ID directly, via get_post(1) works? – Wilhelm Jan 27 '14 at 0:43
  • I don't know why you are seeing what you describe but it should not be that way, and isn't that way when I test it. – s_ha_dum Jan 27 '14 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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