Casbay Knowledge Base

Search our articles or browse by category below

HOW TO: Change the default search URL slug in WordPress

Last modified: October 1, 2022
You are here:
Estimated reading time: 1 min

HOW TO: Change the default search URL slug in WordPress

Change the default search URL slug in WordPress

However, with a few simple tweaks, you can amend the search URL to be more consistent with your site’s permalinks format. Optimizing 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 simply 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.

Select wp-content then select themes
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' );
Change search page slug

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 server and 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.

Change Search URL Slug Using .htaccess

Add the following code to the .htaccess file:

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

 

Change WordPress search URL slug

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.

Was this article helpful?
Dislike 0
Previous: HOW TO: Configure WordPress to work with a new domain
Next: HOW TO: Set up .htaccess redirect