next_posts_link() in the same category

I was wondering if it’s possible to limit next_posts_link() and previous_posts_link() to a specific category in WordPress.

I’ve got a website where I display one post every page. Clicking on next and previous arrow, it goes to next or previous post. However I would like to detect if the next or previous post is in the same category BEFORE loading it and remove prev/next arrow in case the post is not in the same category.

Read More

Here my partial code:

<?php if(in_category( '1' )) {
echo '<section class="next_nav">';
next_post_link('%link', '<img src="http://www.mywebsite.it/wp-content/uploads/2014/11/next_post.png">', TRUE);
echo '</section>';
echo '<section class="previous_nav">';
previous_post_link('%link', '<img src="http://www.mywebsite.it/wp-content/uploads/2014/11/previous_post.png">', TRUE);
echo '</section>';
}

else  {
echo '';
}

?>

When I click on next button, I get the next post but it’s not in the same category. I was wondering if it was possible to use get_next_post() or get_adjacent_post() together with the previous function.

How can I get rid of it ?

Related posts

Leave a Reply