WordPress: Change next post and previous post links to within the same category

1 minute, 4 seconds Read

A quick blog post to document how I changed the Next Post/Previous Post (sometimes known as Newer/Older) to link to posts within the same category. It took a few googles to get the right information, so posting here for ease of reference.

By default, WordPress will link to the next post, regardless of category. With this change, the links will be within the category.

Helpfully, this is a quick theme edit.

1. Search your theme files for the get_next_post() and get_previous_post() function

These functions are typically within the pagination/navigation.php files within WordPress, however in my case, I was unable to find it.

Tip: Download the theme file and open using VSCode/alternate to find the specific function – it is far quicker than searching through the entire theme within the Theme Editor.

2. Add true to the function

Thankfully, WordPress has a flag within the get_next_post() and get_previous_post() function that post determines whether the next/previous post link should be in the same taxonomy term (i.e. category).

This is set to false by default. Therefore, changing the code to;

$next_post = get_next_post(true);
$prev_post = get_previous_post(true);

Will keep the next/previous post links within the same taxonomy/category.

Similar Posts