How to Add Next and Previous Posts Links in WordPress?


Each post in the wordpress is associated with an ID, so you could get its previous and next post which contains the adjacient posts. The wordpress function get_previous_post retrieves the previous post and function get_next_post gets the next post.

So we can have the following function added to the child theme template file functions.php to show these two post links in a single post page. In a page (is_page), these two navigation functions will not work and that is why we need to use is_single() function to exclude other singular pages e.g. is_page() or is_attachment().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
add_filter( 'the_content', 'next_prev_posts' );
 
function next_prev_posts($content) {
  $pages = '';
  if (is_single()) { // only shows on single post, excluding is_page, is_attachment()
    $prev_post = get_previous_post();
    if (!empty( $prev_post )) { // previous post available
        $pages .= "Prev Post: <a href='/archives/".$prev_post->ID."'>$prev_post->post_title</a>";
    }  
    $next_post = get_next_post();
    if (!empty( $next_post )) { // next item available
        $pages .= " | Next Post: <a href='/archives/".$next_post->ID."'>$next_post->post_title</a>";
    }
  }
  return $content . $pages; // put the navigation at the end of the post content
}
add_filter( 'the_content', 'next_prev_posts' );

function next_prev_posts($content) {
  $pages = '';
  if (is_single()) { // only shows on single post, excluding is_page, is_attachment()
    $prev_post = get_previous_post();
    if (!empty( $prev_post )) { // previous post available
        $pages .= "Prev Post: <a href='/archives/".$prev_post->ID."'>$prev_post->post_title</a>";
    }  
    $next_post = get_next_post();
    if (!empty( $next_post )) { // next item available
        $pages .= " | Next Post: <a href='/archives/".$next_post->ID."'>$next_post->post_title</a>";
    }
  }
  return $content . $pages; // put the navigation at the end of the post content
}

Please note that you should adjust your preferred wordpress post URLs which basically can be constructed by the following 3 methods.

  • guid
  • ID
  • post_title

Clear the cache and you should have these two links added after the content of each post. You can also enable the keyboard arrow keys to navigate to neighbour posts.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
394 words
Last Post: Google Webmaster Reports Uncommon Downloads or Harmful Contents
Next Post: How to Get Notified when Vultr Balance is Falling Below Threshold?

The Permanent URL is: How to Add Next and Previous Posts Links in WordPress?

Leave a Reply