I’m using next_post_link
and previous_post_link
on my single post templates, to navigate from post to post, so far so good.
But if I do a search and click on a result post, then the next_post_link
doesn’t bring me to the next result post, but to the next post in the default post order.
Is there a way to make next_post_link
and previous_post_link
behave in different ways depending on the context ? When in a search context, browse only within search results, etc.
EDIT : I’m looking for a solution that would work with custom post types.
Building on Bainternet’s answer above, but making it more generic, I wrote this quick plugin. You can probably modify the link building function at the bottom to do what you want more exactly.
For a custom post type, you’ll probably have to change the ‘post_link’ filter to a ‘post_type_link’ filter. You’ll also need to adjust the function to check for the custom post type. Like so:
and
Down in the get_search_context_adjacent_link function, you’ll need to change the post_type value in the query there as well.
That is not the way WordPress Works, meaning that once you enter s single post from the search results you lose the search context and WordPress can’t tell if you came for the search results, an archive, category page or whatever.
The only way i can think of to by pass that is to create your custom search results page where you should add parameters to the single post link which will hold the search query string and the result’s number for example:
then in your single.php file where you use
next_post_link
andprevious_post_link
check if you came form search results before printing it and if you did then create a query to get the right links, something like:It’s messy and probably not the most efficient way to do it but it works.