How do I restart my loop with get_next_post()?

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:

Read More
    <?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.

Related posts

1 comment

  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.

Comments are closed.