Infinite next and previous post looping in WordPress

It has happened to me several times in my career as a WordPress freelancer to be in need of a infinite next and previous post looping in WordPress. And I have a solution for that.

By default WordPress will show no previous post link when you are viewing the first post and no next post link when you are viewing the last post. But there are cases when an apparently infinite looping is needed. To achieve that, what we practically need to do is when viewing the first post, the previous post link will jump you to the last post and when viewing the last post the next post link will jump to the first post.

The only issue that arises at this point is how do we know that we are are viewing the first post or the last post. WordPress comes to help at this point by providing the get_adjacent_post(). This function allows us to check if there is a next or previous post or not, and if there is not, we will provide one by querying the appropriate one with WP_Query().

Here is the finished code:

I hope this was helpful. Until next time, stay blessed!

You may also enjoy…