Rewrite Search Result URL for WordPress
by c.bavota | Posted in Tutorials | 11 comments
If you have ever done a search on a WordPress site you have probably noticed that the URL ends up looking something like this:
http://your-site.com/?s=searchterm
Even if you have set up your site to display pretty permalinks you will still get that “s” parameter in your URL. For some reason, WordPress does not rewrite the search results URL even though a “pretty” search result URL exists somewhere in the core functions.
Try typing this into your site (remember to replace your-site.com with your URL):
http://your-site.com/search/the
You will get a search results page with actual results for the search term “the.” So the function exists but the rewrite rule does not. You will need to add this function to your functions.php file to put a rewrite rule in place:
function search_url_rewrite_rule() {
if ( is_search() && !empty($_GET['s'])) {
wp_redirect(home_url("/search/") . urlencode(get_query_var('s')));
exit();
}
}
add_action('template_redirect', 'search_url_rewrite_rule');
This function will now rewrite every search results URL to something like this:
http://your-site.com/search/searchterm
I have just implemented this technique on bavotasan.com so do a search to test it out.



is it better for seo? or why should i do that?
Better for looking
It’s better for SEO since the search result page URLs will now be SEO friendly.
Should we make the change in “Edit Themes”/theme-editor? About how far down in the list is “function search…”. I am having difficulty finding it (not an html person). Thank you.
You can make the change in the WP editor but if you make a mistake it can lock you out. The file you want to modify is functions.php and you can add the above code all the way at the bottom. Just make sure that is it included within the PHP tags.
Nice one! I’ll give it a shot. Thanks for all those hints. Great Blog! Cheers!
Hello,
I have a question for it,
how we can change the wordpress search base ($search_base) in wp-includes/rewrite.php automatically from theme options without need to edit the file directly?
thanks a lot!