Next and Previous Links with Loop on Single Pages in WordPress

Sep
20
Wordpress Advanced Tutorials

If you are looking for a relatively easy way to create a looping navigation between single posts in the same category in WordPress, then this might help. This works well for websites that have portfolios or single items that are related, providing a convenient “next” and “previous” link for the visitor.

To start off check out the get_adjacent_post() function on WordPress Codex. This basically returns the values or information of the post adjacent to the current viewed post on the single page. The code below is an example of a link to the ‘next’ post.

The values from the ‘next’ post are stored as an array in the variable $next. The permalink is extracted for that specific post from $next by using the get_permalink() function, and stored as $permalinknext for easier use in the link. To create the link use a simple php ‘if (!empty())’ statement to check if the $next variable isn’t empty, and if it isn’t empty; echo the link for the ‘next’ post with a title and class for styling.

For the ‘previous’ link the code stays much the same except the parameters of the get_adjacent_post() need to be changed and variables named correctly.

While this is really useful, the ‘next’ and ‘previous’ links obviously disappear when you reach the end of the category, but some of you may want the navigation to loop through the whole category again and return to the start. For this you will have to retrieve both the permalinks for the first and last post to use in the if statement for when the variables $next, and $previous are empty.

Change ‘category’ => 4 to the category you are using. You can see what ID is assigned to a category by hovering over it in the WordPress backend under the categories tab and checking the link url.

By putting everything together you can create links for when the category reaches the end. The code bellow is a full example of ‘next’ and ‘previous’ navigation on a single page with looping functionality.

Post a Comment

Name and Email required. Email will not be published.

Comment

css.php