This hook fires for pretty much everything WordPress does, every time anythign is displayed there is a search of some sort going on. You can use it to alter the results the search returns.
The $Query object class
The $Query object that is passed to the hook shouldn’t be altered, but can be used to do lots of things – see here.
Examples
Filtering search results to user doing a search using a search box
add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts($Query)
{
//Do not change queries in the admin screens
if (is_admin())
return;
//Only modify the main search query on the front end
if (!$Query->is_main_query())
return;
if ($Query->is_search())
{
//----------------------------------------
//----- THIS IS A SEARCH BY THE USER -----
//----------------------------------------
$UrlWithoutArguments = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH); //Get page without any url arguments
if($UrlWithoutArguments == '/my_search_results')
{
//USER DOING A SEARCH ON PAGE /my_search_results
//Filter by author user_id's
$AllowedUserIds = [2, 5, 10]; // Replace with your desired user IDs
if (count($local_vendor_user_ids) > 0)
$Query->set('author__in', $AllowedUserIds);
else
$Query->set('author__in', array(0)); //If you return an empty array it will be ignored, to force no results use value 0 as it won't exist
}
} //if ($Query->is_search())
}
