Previous Next Post Navigation for Multiple Post Types at once

Previous and Next Navigation for both Posts and Pages.
To create these beautiful navigation arrows I used get_previous_post() and get_next_post() functions.

WordPress has a great action hook that allows to change WHERE statement and affects all of the prev/next navigation functions.


add_action( 'get_previous_post_where', 'misha_posts_and_page', 20 );
add_action( 'get_next_post_where', 'misha_posts_and_page', 20 );
 
function misha_posts_and_page( $where ){
	// $where looks like WHERE p.post_date < '2017-08-02 09:07:03' AND p.post_type = 'post' AND ( p.post_status = 'publish' OR p.post_status = 'private' )
	// In code $where looks like $wpdb->prepare( "WHERE p.post_date $op %s AND p.post_type = %s $where", $post->post_date, $post->post_type )
	// Parameters $op and another $where can not be passed to this action hook
	// So, I think the best way is to use str_replace()
	return str_replace(
		array( "p.post_type = 'post'", "p.post_type = 'page'" ),
		"(p.post_type = 'post' OR p.post_type = 'page')",
		$where
	);
 
}

For three post types the str_replace() part of the code will look like this:

return str_replace(
	array( "p.post_type = 'post'", "p.post_type = 'page'", "p.post_type = 'product'" ),
	"(p.post_type = 'post' OR p.post_type = 'page' OR p.post_type = 'product')",
	$where
);

This action hook affects all the post prev/next navigation functions, such as next_post_link(), previous_post_link(), get_previous_post_link(), get_next_post_link(), adjacent_post_link(), get_adjacent_post_link(), the_post_navigation(), get_previous_post(), get_next_post, get_adjacent_post()

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on Twitter