The default url of wordpress search page may like:
https://www.tutorialexample.com/?s=lstm
It ends with ?s=keyword
If you plan to change it, how to do?
In this tutorial, we will introduce you the way to change wordpress search url.
For example, we plan to change
https://www.example.com/?s=lstm
to
https://www.example.com/model/lstm/
The full code is below:
add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' ); add_filter( 'query_vars','my_insert_query_vars' ); add_action( 'wp_loaded','my_flush_rules' ); // flush_rules() if our rules are not yet included function my_flush_rules(){ $rules = get_option( 'rewrite_rules' ); if ( ! isset( $rules['model/(.*)'] ) ) { global $wp_rewrite; $wp_rewrite->flush_rules(); } } // Adding a new rule function my_insert_rewrite_rules( $rules ) { $newrules = array(); $newrules['^model/(.+)/page/?([0-9]{1,})/?$'] = 'index.php?s=$matches[1]&paged=$matches[2]'; $newrules['^model/(.+)/?$'] = 'index.php?s=$matches[1]'; return $newrules + $rules; } function my_insert_query_vars( $vars ) { array_push($vars, 's'); return $vars; }
You can copy and save this code in your theme functions.php
add_action( 'wp_loaded','my_flush_rules' );
This code will call my_flush_rules to flush wordpress rewrite rule.
my_insert_rewrite_rules function convert ?s=keyword to /model/keyword.
Then you will find the effect of https://www.example.com/?s=lstm and https://www.example.com/model/lstm/ is the same.
After we have changed the url of wordpress url, we have to redirect ?s=keyword to /model/keyword/ using 301. We can use some wordpress 301 redirection plugins to implement it or we process it in search.php.