Restrict the post navigation to the same category


Note :This snippet works only with the Classical style option. The Classical style option can be enabled in Appearance > Customize > Advanced > Theme Style. More about the theme style option here


WordPress offers built-in functions to display the previous and next post link.

 

As you can see there’s a boolean parameter named ‘in_same_term’.

This allows you to :

Indicates whether previous post must be within the same taxonomy term as the current post. If set to 'true', only posts from the current taxonomy term will be displayed. If the post is in both the parent and subcategory, or more than one term, the previous post link will lead to the previous post in any of those terms.

More documentation for those functions here.

Very handy !

 

But there are some cases when you need to go a bit further into coding. Typically, if you don’t want to modify a parent theme and rather customize it from a child theme.

 

Let’s say you have a theme with a custom display for your post navigation links, like the one used in the Customizr theme :

 

In the above code, the in_same_term parameter is not set. To display the prev/next post link of the same category, we then have to filter the default behaviour or WordPress with the hooks API provided in wp-includes/link-template .

Note : Since Customizr 3.3.* (Customizr-Pro) two new filters have been added to simplify this process

Where to copy/paste this code?
Add it to your child-theme functions.php.
Everything you need to know about creating a child theme with Customizr here.
Note :  Following the old Code for Customizr 3.2.* and below

Here’s the code that will allow you to restrict the post navigation to the same category :

(Paste it in your functions.php)

 


Related Snippets you may also like


6 thoughts on “Restrict the post navigation to the same category

Comments are closed.