WordPress doesn’t have SEO-friendly URLs for the search results page, which could lower your SEO ranking. This guide will be helpful if you want to change the default search URL slug in WordPress.
Why Should we change the default search URL slug
Answer is very simple that WordPress by default allows us to use smart URLs which are always SEO friendly. But when it comes to the search result page then the url looks some like https://techTutorialsOnline.com/?s=wordpress
which is neither user friendly nor SEO friendly. This can result in confusing the users and search engines.
This was basics about what we have with WordPress for SEO friendly URLs but lets go ahead and change the default search URL slug in WordPress.
There are two methods to achieve this.
- Adding code to active theme’s
functions.php
or plugin - Adding code to the
.htaccess
file at root of WordPress
Method 1 – Add code to functions.php file
function techTutorialsOnlineChangeSearchUrl() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
exit();
}
}
add_action( 'template_redirect', 'techTutorialsOnlineChangeSearchUrl' );
Code explanation:
The code above will use the action hook “template_redirect” that is responsible for checking which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried.
The second parameter is the callback function which will actually override the default hook. Inside the function, we are checking if the requested template page is search result page. If so then add a redirect to the search slug with search keyword.
Method 2 – Add code to .htaccess file
Add the following code to the .htaccess
file at the root of your WordPress project.
# Change The Default Search URL Slug In WordPress
RewriteCond %{QUERY_STRING} \?s=([^&]+) [NC]
RewriteRule ^$ /search/%1/? [NC,R,L]
Note: Please make sure you have taken a backup.
That is it. Now try the search form and now the default search URL slug will look something like https://techTutorialsOnline.com/search/wordpress.
Cheers!!!!
Feel free to comment incase of any issue.