HOW TO: Change the default search URL slug in WordPress

Last modified: April 13, 2020
You are here:
Estimated reading time: 1 min

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

Wordpress-wp-content-themes
Select wp-content > 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' );

Wordpress-code-change search page slug
Copy and paste the code in .php file:

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.

Wordpress-change search URL Slug
Change search URL Slug

 

Add the following code to the .htaccess file:

# Change WordPress search URL slug
RewriteCond %{QUERY_STRING} \?s=([^&]+) [NC]
RewriteRule ^$ /search/%1/? [NC,R,L]
Wordpress-code-change wordpress search URL slug-.htaccess file
Add the following code to the .htaccess file

 

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
Views: 41