By default, WordPress shows the next post and previous post according to published time irrespective of category. But many WordPress publishers need to show their next post and previous post from the same category. In this tutorial, you will learn how to display the next post and previous post from the same category in WordPress.

Next and Previous Post From Same Category in WordPress

By default, in WordPress next/previous post displays posts starting from the newest and proceeding backwards in time (after post 1 would post 2 from the same/different category). But, You can control the next and previous so that it works within the same categories only. When you click the next/previous post link, It will redirect to the next post/previous post of the same category, instead of a post from a different category.

Below code can be used to display the next/previous post within the same category, and tested on the Astra WordPress theme. Generally, this code will work for most of the WordPress themes, not only for the Astra theme to show the next/previous post within the same category.

Code for restricting Next and Previous Post From Same Category / Taxonomies in WordPress

  • Before using this code on your WordPress website, keep a backup of your site.
  • Paste this code in the function.php file
  • Always use a child theme
add_filter( 'get_next_post_join', 'navigate_in_same_taxonomy_join', 20);
add_filter( 'get_previous_post_join', 'navigate_in_same_taxonomy_join', 20 );
function navigate_in_same_taxonomy_join() {
	global $wpdb;
	return " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
}


add_filter( 'get_next_post_where' , 'navigate_in_same_taxonomy_where' );
add_filter( 'get_previous_post_where' , 'navigate_in_same_taxonomy_where' );
function navigate_in_same_taxonomy_where( $original ) {
	global $wpdb, $post;
	$where 		= '';
	$taxonomy  	= 'category';
	$op 		= ('get_previous_post_where' == current_filter()) ? '<' : '>';
	$where 		= $wpdb->prepare( "AND tt.taxonomy = %s", $taxonomy );
	if ( ! is_object_in_taxonomy( $post->post_type, $taxonomy ) )
		return $original ;

	$term_array = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );

	$term_array = array_map( 'intval', $term_array );

	if ( ! $term_array || is_wp_error( $term_array ) )
		return $original ;

	$where 		= " AND tt.term_id IN (" . implode( ',', $term_array ) . ")";
	return $wpdb->prepare( "WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $where", $post->post_date, $post->post_type );
}

 

 

Sharing is Caring
Scroll to Top