How-to Create Clean Search Links in WordPress

When you or a visitor performs a search on a WordPress site, the search result link looks like this:

Where Brandon is what your or the visitor was searching for. However, that doesn’t look pretty and if you use permalinks, it does not match the permalink structure, so why not make the search link pretty?

This is what the pretty search link will look like, using Brandon as the search word:

To create clean search links using a function or plugin, you’ll need to have permalinks enabled. You can check Settings > Permalinks to see if you have enabled pretty permalinks.

Create a Function

To make a pretty search link, use the following code snippet by adding it to your theme’s functions.php file:

// Clean search permalinks /?s= to /search/ function clean_search_link() { global $wp_rewrite; if ( !isset( $wp_rewrite ) || !is_object( $wp_rewrite ) || !$wp_rewrite->using_permalinks() ) return; $search_base = $wp_rewrite->search_base; if ( is_search() && !is_admin() && strpos( $_SERVER['REQUEST_URI'], "/{$search_base}/" ) === false ) { wp_redirect( home_url( "/{$search_base}/" . urlencode( get_query_var( 's' ) ) ) ); exit(); } } add_action( 'template_redirect', 'clean_search_link' );

We are creating a function called cleansearchlink that uses wp_rewrite, which is a WordPress class used for rewrite rules.

That’s it, just add the function to your theme’s functions.php file. There is no need to modify the searchform.php file or any other file.

Use the Plugin

There is a plugin, which the function version is based on, that can do this for you, called Nice Search; just install and activate.

Unlike the function version, there is no need to touch the theme’s functions.php file (or any other file).