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 suggestion.

Related posts

Leave a Reply

1 comment

  1. you can’t do it with get_next_post – full stop.

    Here’s how I’ve done it…

    <?php
    /**
    * Infinite next and previous post looping in WordPress
    */
    
    $next_post = get_next_post();
    $previous_post = get_previous_post();
    $current_id = get_the_ID();
    
    // Get ID's of posts
    $next_id = $next_post->ID;
    $previous_id = $previous_post->ID;
    $prev_title = strip_tags(str_replace('"', '', $previous_post->post_title));
    $next_title = strip_tags(str_replace('"', '', $next_post->post_title));
    
    // get the first posts ID etc
    $args = array('post_type'=>'project', 'posts_per_page' => -1);
    $posts = get_posts($args);
    $first_id = $posts[0]->ID;
    $first_title = get_the_title( $first_id );
    
    
    // get the last posts ID etc
    $last_post = end($posts);
    $last_id =  $last_post->ID; // To get ID of last post in custom post type outside of loop
    $last_title = get_the_title( $last_id );
    
    // if the current post isn't the first post
    if($current_id != $first_id) { ?>
        <a href="<?php echo get_permalink($previous_id) ?>" title="<?php $prev_title ?>" class="prev-next prev">Previous Project:<?php echo $prev_title; ?></a>
    
    <?php    
     // if the current post is the first post
    } else { ?>
        <a href="<?php echo get_permalink($last_id) ?>" title="<?php $last_title ?>" class="prev-next prev"> Previous Project</a>
    <?php }; ?>
    
    <?php 
    // if the current post isn't the last post
    if($current_id != $last_id) { ?>
        <a rel="next" href="<?php echo get_permalink($next_id) ?>" title="<?php $next_title ?>" class="prev-next next"> Next Project <?php  echo $next_title; ?></a>
    
    <?php 
    // if the current post is the last post
    }  else { ?>
        <a rel="next" href="<?php echo get_permalink($first_id) ?>" title="<?php $last_title ?>" class="prev-next next">  Next Project <?php echo $first_title; ?></a>
    <?php } ?>
    

    Elements take from here Getting first & last post in custom post type outside of loop