This is what I’m using to output my post navigation:
<?php if (is_single() ) { ?>
<nav class="post-navigation">
<h1 class="visuallyhidden">Post Navigation</h1>
<ul>
<li class="prev"><?php previous_post_link('%link', '%title', 'in_same_cat'); ?></li>
<li class="next"><?php next_post_link('%link', '%title', 'in_same_cat'); ?></li>
</ul>
</nav>
<?php } ?>
This will restrict the navigation to the current category (sub and parent category).
I’d like to restrict this to only the current sub category. What would be the best way to do this?
As @Ravs mentions the third parameter in
next_post_link()
/previous_post_link()
should be a boolean value indicating whether to restrict the link to a post in the same category. By default this is false. If set to true, it will choose the next (or previous) post which is in the same category as the current post. This includes all parent & child categories.The functions accept a third parameter: an array of category IDs to be excluded – but as pointed out in the comments, you cannot exclude categories to which the post belongs if you set the ‘in same category’ argument to true.
So one solution is to set ‘in same category’ to
false
, and exclude all terms which are not associated with a post, or which are, but have a child who is also associated with a post. (This is fairly messy, you can use the SQL filters if you prefer)The following returns terms that are associated with a post, and who have child terms also associated with the post:
Example usage:
Health warning: I don’t perform any checks so you may get errors if the post has no terms etc. The following logic to get
$exclude_these
should be wrapped up in a function and moved out of the template for readability. I got lazy.you code may be look like
put
TRUE
insteadin_same_cat
.in_same_cat
is a parameter which have valueTRUE
orFAlSE
(default)Important link:
previous_post_link