Skip to content

Instantly share code, notes, and snippets.

@banago
Last active March 28, 2024 11:31
Show Gist options
  • Save banago/5603826 to your computer and use it in GitHub Desktop.
Save banago/5603826 to your computer and use it in GitHub Desktop.
Infinite next and previous post looping in WordPress
<?php
/**
* Infinite next and previous post looping in WordPress
*/
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', '&larr; Previous Post');
} else {
$first = new WP_Query('posts_per_page=1&order=DESC'); $first->the_post();
echo '<a href="' . get_permalink() . '">&larr; Previous Post</a>';
wp_reset_query();
};
if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', 'Next Post &rarr;');
} else {
$last = new WP_Query('posts_per_page=1&order=ASC'); $last->the_post();
echo '<a href="' . get_permalink() . '">Next Post &rarr;</a>';
wp_reset_query();
};
@cabrailsford
Copy link

Just as a head's up, you should probably be using wp_reset_postdata(), not wp_reset_query(), since the latter is typically only used if you're using query_posts and not WP_Query.

@nanoanno
Copy link

This was super helpful and worked like a charm. Thanks!

@Mishkamshka
Copy link

Mishkamshka commented Dec 26, 2021

Hi everyone, @amouratoglou I had the same problem. Thanks @cabrailsford for the heads up.
Heres the fix:
` <?php

if( get_adjacent_post(false, '', false) ) { 
    next_post_link('%link', '&larr; Previous project');
} else { 
        $first = new WP_Query('post_type=CHANGETHIS&posts_per_page=1&order=ASC'); $first->the_post();
    echo '<a href="' . get_permalink() . '">&larr; Previous project</a>';
    wp_reset_postdata();
}; 


if( get_adjacent_post(false, '', true) ) { 
    previous_post_link('%link', 'Next project &rarr;');
} else { 

        $last = new WP_Query('post_type=CHANGETHIS&posts_per_page=1&order=DESC'); $last->the_post();

    echo '<a href="' . get_permalink() . '">Next project &rarr;</a>';
    wp_reset_postdata();
}; 

?>`

@catcodru
Copy link

catcodru commented Mar 28, 2024

Hi)
this work for me (don't forget change post type):

if( get_adjacent_post(false, '', true) ) { 
	previous_post_link('%link', '&larr; %title');
} else { 
    $first = new WP_Query('post_type=projects&posts_per_page=1&order=DESC'); $first->the_post();
    	echo '<a href="' . get_permalink() . '">&larr; '. get_the_title() .'</a>';
  	wp_reset_query();
}; 
    
if( get_adjacent_post(false, '', false) ) { 
	next_post_link('%link', '%title &rarr;');
} else { 
	$last = new WP_Query('post_type=projects&posts_per_page=1&order=ASC'); 
	$last->the_post();
    	echo '<a href="' . get_permalink() . '">'. get_the_title() .' &rarr;</a>';
    wp_reset_query();
}; 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment