Change query variable for wordpress search

When we do a search in wordpress the url appears like this:

http://example.com?s=hello

But I am using s= query variable for another purpose. so I wish to change default wordpress s= to search=.

Read More

The updated code should not work of s= for wordpress search, instead it should only support search=.

I tried a code snippet from http://demand.cr/2011/08/how-to-replace-the-default-search-query-parameter-in-wordpress/. It works but it accepts both s= and search=. I need it to work only for search=

Related posts

2 comments

  1. The code you found works not by changing the query variable but by converting another variable into the s variable that WordPress expects.

    If you look at the WP_Query object, that s parameter is pretty deeply embedded into Core functionality.

    The simple solution, and perhaps the only one, is to choose some other parameter for your purpose rather than attempt to hijack one that is hard-coded into fundamental Core WordPress code.

  2. I was looking for the same solution and I couldn’t find one. The link in the original question doesn’t work anymore so I am not sure how the code was.
    This is how I managed to do it:

    //Remove the default search var and add a custom one
    add_filter('init', function(){
        global $wp;
        $wp->add_query_var( 'search' );
        $wp->remove_query_var( 's' );
    } );
    
    //If the custom var is passed copy that over to the default "s" var
    add_filter( 'request', function( $request ){
        if( isset( $_REQUEST['search'] ) ){
            $request['s'] = $_REQUEST['search'];
        }
        return $request;
    } );
    

    I have tested this with the default search and WooCommerce search and it worked for both.
    Once the code has been added to the functions.php it is also necessary to change all search forms to use the new query var instead of the “s” in the input field:

    <input type="search" class="search-field" placeholder="Search …" value="" name="search">
    

Comments are closed.