I was wondering how I would go about customizing search results based on which page the user is currently on in my Wordpress site.
I'm building a support/help center style website for a system that contains multiple versions, and I would like the search results to be based on which "version" the user is looking at.
Here's some more context, I have:
system.com/version1
system.com/version2
If a user uses a search form on a page in /version1, I would like the results to be only pages also in /version1. If a user uses a search form on a page in /version2, I would like the results to be from /version2
Is this possible, and if so what would be the easiest way to go about implementing it?
Thanks,
You could try using the pre_get_posts
action hook. This will allow you to modify the query
object depending on what page you are on. Documentation here.
I haven't been able to test this yet, but you might start with something like this:
function my_children_query( $query ) {
global $post; // not sure if this is needed
// do nothing if we aren't on a search page
if( !$query->is_search) {
return;
}
// get only children of current page
if( is_page( 'something1' ) || is_page( 'something2' ) ) {
$query->set( 'post_parent', $post->ID );
}
}
add_action( 'pre_get_posts', 'my_children_query' );