Showing Relevant Next/Previous Blog Posts

Show Next/Previous Links

Sometimes when you build a WordPress theme you may want you to only show relevant Next and Previous post links. For instance, if you created a specific category for your “Galleries” and only used the “Gallery” Post format in that category you might want to ONLY show other Galleries in the post navigation. Here’s how you do that.

First off, here’s the HTML for the navigation:

<div class="navigation">
<div class="alignleft"><!-- Previous Post Link --></div>
<div class="alignright"><!-- Next Post Link --></div>

The code we’ll need to show the Next and Previous post links is:

<?php previous_post_link(''); ?>
<?php next_post_link(''); ?>

Now, let’s customize the PHP to show our relevant Posts from that specific category only.

<?php previous_post_link('%link', 'Previous post', TRUE); ?>
<?php next_post_link('%link', 'Next post', TRUE); ?>

Here’s an explanation of the above code.

  1. %link – This will show the link for the previously or recently published Post from the one being viewed.
  2. Previous post/Next post – This will be the anchor text for the respective links.
  3. TRUE – This will tell the code to only use the same category as the Post being viewed to show the relevant links.

Here’s the final code:

<div class="navigation">
<div class="alignleft"><?php previous_post_link('%link', 'Previous post', TRUE); ?></div>
<div class="alignright"><?php next_post_link('%link', 'Next post', TRUE); ?></div>

You can use the CSS classes to format the output however you like. You can see an example of this type of navigation at the very bottom of this post.

If you found this tutorial helpful please consider tweeting or liking it! Do add your comment below on how you’ve used it!

One thought on “Showing Relevant Next/Previous Blog Posts

  1. i was surprised to find someone having wrote about this, i think youre the only one, that i have found at least.. .

    could you update this post though for people not that experienced, such as how would i go about implementing this in a current theme, through child them functions…


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.