Infinite next and previous post looping in WordPress

Infinite next and previous post looping in WordPress

If you are trying to find out which is your first post and last post you can add below function in your function.php file

<?php

/********************
* get first post
********************/

function aman_first_post() {
global $post;
$loop = get_posts( 'numberposts=1&amp;order=ASC' );
$first = $loop[0]-&gt;ID;
return ( $post-&gt;ID == $first ) ? true : false;
}


/********************
* get last post
********************/

function amn_last_post() {
 global $post;
 $loop = get_posts( 'numberposts=1' );
 $latest = $loop[0]-&gt;ID;
 return ( $post-&gt;ID == $latest ) ? true : false;
}?>

and call the function.

Use in loop (in single.php file) to add link of last post as previous post on first post and add “amn_last_post” function

<?php
if ( amn_last_post() ) {

if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', 'Next Post →');
} else {
$last = new WP_Query('posts_per_page=1&order=ASC'); $last->the_post();
echo 'Next Post →';

wp_reset_query();
};

}?>

use in loop (in single.php file) to add link of first post as next post on last post and add “amn_first_post” function in functions.php file

<?php
if ( amn_first_post() ) {

if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', '← Previous Post');
} else {
$first = new WP_Query('posts_per_page=1&order=DESC'); $first->the_post();
echo '← Previous Post'; wp_reset_query(); }; } ?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: