Change the Search Results Page URL Slug to ‘/search/term’

How to Change the Search Results Page URL Slug to ‘/search/term’

in Search
Google+ LinkedIn

Default WordPress URL Structure is not the most Search Engine friendly, and it certainly is not very user friendly too. But WordPress has built in option to enable SEO friendly URLs to make URLs more user friendly. All you need to do is to login to WordPress admin panel and pick a permalink structure of your choice on Permalink Option page. Enabling SEO friendly URLs on your website will force WordPress to follow permalink structure for most part of the website but it wouldn’t change search results page URL which by default is “/?s=term“. So in this topic we will see how we can change it to more user friendly and rewrite the search results page URL slug to “/search/term“.

For this purpose we will use template_redirect action hook. We will first check if a user is accessing search results page and if search does not return empty results. If both of the conditions are true then WordPress will redirect user to “/search/term” link instead of default “/?s=term”. Following is the function we wrote to change the search results page URL slug to ‘/search/term’. You can paste this code in your theme’s functions.php file without any modification.

// change the search results page URL slug
function wpcs_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', 'wpcs_search_url_rewrite_rule' );

That’s it. Now your users are redirecting to “/search/term” search results page URL.

Share the love

If you like this snippet, share it with others!

4 Replies on "Change the Search Results Page URL Slug to ‘/search/term’"

  1. Toby

    HI
    I tried this for my woocommerce shop and that resulted in products displayed as a blog post. Can you use this, but the products are shown as a product?

    Thanks!

    1. It’s possible.

      You will need to replace item template for search results. Right now it’s using default content.php template.

      1. Toby

        Okej that sounds great!

        Can you tell me how and where I could do that?

        Thank you so much!

      2. Toby

        Okej, can you tell me how?

        Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *