Previous Next Post Navigation for Multiple Post Types at once

By default when you want to display links to previous next posts, WordPress will show the same post type as the current post. In this tutorial we will make it work for both Posts and Pages at once.

/1 comment
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')",

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')",

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

I love WordPress, WooCommerce and Gutenberg so much. 10 yrs of experience.

Need some custom developer help? Let me know

Follow Misha

Need some help with WordPress?

If you need some professional developer help, I will be happy to assist you.

Contact me Who I am?

Comments — 1

Leave a comment

php js HTML CSS Code