I am trying to use the pre_get_posts hook to replace WordPress’s search function with my own, so I want to unset $query->query_vars[‘s’] so that it does not restrict the results, but I want to keep ‘s’ as a property of $query so that I can use the get_search_query function. How would I go about doing this?
add_action('pre_get_posts', function (WP_Query $query) {
if (!$query->is_search()) {
return;
}
if (is_admin()) {
return;
}
$q = get_search_query();
if (!$q) {
return;
}
$search_parameters = array("q" => $q);
$search_parameters = apply_filters('custom_search_parameters', $search_parameters);
$search_results = custom_search($search_parameters);
if ($search_results) {
unset($query->query_vars['s']); // This causes get_search_query() to no longer work, but omitting it restricts the results.
$query->query_vars['post__in'] = $search_results['post_ids'];
$query->query_vars['orderby'] = 'post__in';
$query = apply_filters('custom_search_query', $query);
}
});