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
$Query->set('author__in', $AllowedUserIds);
}
} //if ($Query->is_search())
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.