Knowledgebase
HOW TO: Change the default search URL slug in WordPress
Posted by Sugen S. on 20 September 2018 04:58 PM

While WordPress can be configured to display posts and pages with SEO-friendly URLs, the platform’s default search URL structure (http://www.mydomain.com/?s=search-term) is less attractive for search engine crawlers.

However, with a few simple tweaks, you can amend the search URL to be more consistent with your site’s permalinks format, optimising search pages for search engines.

Amend Your Site’s Functions File

The easiest way to change your search page slug is to edit your site’s functions.php file. You can download the file using an FTP client, then edit the file locally using a text editor or simple use cPanel File Manager in the HostPapa Dashboard to edit the file directly on the server.

Head to your WordPress site root, then select wp-content > themes.  Open the directory pertaining to your active WordPress theme.

Copy and paste the following code at the bottom of the functions.php file:

/**
* Change search page slug.
*/

function wp_change_search_url() {
    if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
        exit();
    }  
}
add_action( 'template_redirect', 'wp_change_search_url' );

 

Save the file (and upload to the server, if required), then head to your site’s front-end and use your search feature. Notice how the URL structure has changed to http://www.mydomain.com/search/search-term.

Change Search URL Slug Using .htaccess

The alternative method to change your search URL slug is to use a .htaccess rule. .htaccess is a configuration file used by the Apache web serverand can be used to rewrite the format of URLs.

The .htaccess file can be found in your WordPress root folder. Download with an FTP client and edit with a text editor application, or use cPanel File Manager once again to edit the file directly on the server.

Add the following code to the .htaccess file:

# Change WordPress search URL slug
RewriteCond %{QUERY_STRING} \\?s=([^&]+) [NC]
RewriteRule ^$ /search/%1/? [NC,R,L]

Save the file (and upload to the server, if required), then head to your site’s front-end and use your search feature. Notice again how the URL structure has changed.

(0 vote(s))
Helpful
Not helpful

Comments (0)
Copyright © 1998 - 2018 Shinjiru International Inc. All Rights Reserved.