Output only links or url for the next or previous post in WordPress

This is a common feature that we quite often want to use Next Post or Previous Post button in our WordPress blog to give better internal link structure, user engagement, and user interaction on our website.

This is easily doable by a WordPress function = get_adjacent_post

get_adjacent_post( bool $in_same_term = false, int[]|string $excluded_terms = '', bool $previous = true, string $taxonomy = 'category' )

I am providing the final snippet that must work like a charm.

<?php 
  $prev_post = get_adjacent_post(false, '', true);
  $next_post = get_adjacent_post(false, '', false);
  if(!empty($prev_post)) {
    echo '<a href="' . get_permalink($prev_post->ID) . '" title="' . $prev_post->post_title . '">' . 'Previous Post' . '</a>';
  }
  if(!empty($next_post)) {
    echo '<a href="' . get_permalink($next_post->ID) . '" title="' . $next_post->post_title . '">' . 'Next Post' . '</a>';
  }
?>    

The final output in the browser is like this:

Please let us know if you have any questions or suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *