最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change query variable for wordpress search

programmeradmin4浏览0评论

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


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

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

I tried a code snippet from /. It works but it accepts both s= and search=. I need it to work only for search=

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

http://example?s=hello

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

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=

Share Improve this question edited Jul 29, 2013 at 23:58 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Jul 29, 2013 at 3:17 Joby JosephJoby Joseph 1251 silver badge6 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 4

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.

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">
发布评论

评论列表(0)

  1. 暂无评论