How to make my pagination loop continuously?

So I created some custom pagination for my single.php template to show next/previous posts at the bottom. However, the way it is working currently is linear(ie on the most recent post there is only a “next post” link and on the oldest post there is only a “previous” post link).

What I would like to do is make the loop continuous, so that on the first post, the “next post” link will be to the second newest post and the “previous post” link will be the oldest post.

Here’s my pagination code:

<?php 
    $nextPost = get_next_post();
    if($nextPost) {
        $nextPostID = $nextPost->ID;
?>
    <a class="prev-post" href="https://wordpress.stackexchange.com/questions/270728/<?php echo get_permalink( $nextPostID ); ?>">
        <?php pagination_next($nextPostID); ?>
    </a>
<?php } ?>

<?php 
    $prevPost = get_previous_post();
    if($prevPost) {
        $prevPostID = $prevPost->ID;
?>
    <a class="next-post" href="<?php echo get_permalink( $prevPostID ); ?>">
        <?php pagination_prev($prevPostID); ?>
    </a>
<?php } ?>

1 Answer
1

You could add an else to both ifs and get the first post/latest post:

<?php 
     $nextPost = get_next_post();
    if($nextPost) {
        $nextPostID = $nextPost->ID;
?>
    <a class="prev-post" href="https://wordpress.stackexchange.com/questions/270728/<?php echo get_permalink( $nextPostID ); ?>">
        <?php echo $nextPost->post_title; ?>
    </a>
<?php } else {
        $first_post = get_posts( array(
            'posts_per_page'   => 1,
            'order' => 'ASC'
        ) );
        ?>
        <a class="prev-post" href="<?php echo get_permalink( $first_post[0]->ID ); ?>">
            <?php echo get_the_title( $first_post[0]->ID ); ?>
        </a>

<?php } ?>

<?php
    $prevPost = get_previous_post();
    if($prevPost) {
        $prevPostID = $prevPost->ID;
?>
    <a class="next-post" href="<?php echo get_permalink( $prevPostID ); ?>">
        <?php echo $prevPost->post_title; ?>
    </a>
<?php } else {
    $latest_post = get_posts( array(
        'posts_per_page'   => 1,
        'order' => 'DESC'
    ) );
    ?>
    <a class="next-post" href="<?php echo get_permalink( $latest_post[0]->ID ); ?>">
        <?php echo get_the_title( $latest_post[0]->ID ); ?>
    </a>
<?php } ?>

I’m assuming you want this only for posts, so on get_posts I’m leaving the default post type as post.

Leave a Comment