2

A Wordpress URL that triggers a search includes a s parameter and a value. So, something like https://example.com/?s=hello.

I want Wordpress to not render the search template, but to use whatever template should be shown if the s parameter would not be present.

I can use the template_include hook to force another template to be used, but this still loads the wrong posts.

I can also unset the querystring variable s using the parse_query hook. This then loads search results as if the search was for an empty string. If I also set is_search to false, I get a fatal error as a consequence of some include files (of my theme) being loaded multiple times.

What does work is capturing the s in template_redirect, and redirecting to the same URL but with the s parameter replaced by another parameter (say mys), and then handling that parameter instead on the resulting page. I find this a hack.

How do I make this work without replacing the query string variable?

1 Answer 1

2

How to get Wordpress to ignore the search parameter in the frontend?

What you can try, is hooking in earlier, to remove the public search query variable, like (untested):

add_filter( 'request', function( $qv ) {
    if ( ! is_admin() && isset ( $qv['s'] ) ) {
        unset( $qv['s'] );
    }
    return $qv;
} );

We are here hooking into WP::parse_request() where query variables are first registered into WordPress from GET/POST request parameters.

I can also unset the query string variable s using the parse_query hook. This then loads search results as if the search was for an empty string.

Note that query variables are restored soon after the pre_get_posts hook runs, in case they were unset:

// Fill again in case 'pre_get_posts' unset some vars.
$q = $this->fill_query_vars( $q );

https://github.com/WordPress/wordpress-develop/blob/6.5/src/wp-includes/class-wp-query.php#L1887

3
  • Thanks. I'm not quite clear on the implications of the query variables being restored. However, unsetting the s query string parameter in 'query_vars' in itself did not do the trick; the search template is loaded, and relevant search results are shown. Does this mean I have to clear the s query string variable multiple times?
    – MastaBaba
    Commented May 3 at 17:27
  • Wonder if you could try the request filter (see update) instead, it fires a little bit later than query_vars filter within the same class method WP::parse_request().
    – birgire
    Commented May 3 at 17:53
  • 1
    Yes! Awesome! Thanks!
    – MastaBaba
    Commented May 3 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.