Excluding a category from next and previous post links

I am trying to figure out the code to exclude a category from my next and previous post links.

My code for the next and previous is as follows:

<div class="next_prev_cont">
                    <div class="left">
                         <?php previous_post_link('%link', '<i>Previous post</i><br />%title'); ?> 
                    </div>
                    <div class="right">
                         <?php next_post_link('%link', '<i>Next post</i><br />%title'); ?> 
                    </div>
                    <div class="clear"></div>
                </div><!--//next_prev_cont-->

I believe I need to use the following:
$excluded_terms=”4835″

4835 being the cat ID, but I’m not sure how to implement it? Any help is greatly appreciated!

1 Answer
1

The next_post_link() and previous_post_link() functions have parameteres as follows –

  • $format (string) – You’ve already included this.

  • $link (string) – You’ve already included this.

  • $in_same_term = false (boolean) – Whether or not all linked posts should be within the same taxonomy term. Chances are this should be false if you are looking to exclude a single term.

  • $excluded_terms="" (string|array) – The terms to exclude, as a comma seperated string or an array of integers.

  • $taxonomy = 'category' (string) – Only required if $in_same_cat = true.

So to get your links working as you desire you should do this –

<?php $excluded_terms="4835"; ?>
<div class="next_prev_cont">
    <div class="left">
        <?php previous_post_link('%link', '<i>Previous post</i><br />%title', false, $excluded_terms); ?> 
    </div>
    <div class="right">
        <?php next_post_link('%link', '<i>Next post</i><br />%title', false, $excluded_terms); ?> 
    </div>
    <div class="clear"></div>

I recommend you take a few moment to read the related function referneces for these two functions –

  • next_post_link() – http://codex.wordpress.org/Function_Reference/next_post_link
  • previous_post_link() – http://codex.wordpress.org/Function_Reference/previous_post_link

Leave a Comment