SEO PHP Intermediate

Use Pretty Search URLs

Redirect search results from ?s=term to /search/term/, which is cleaner to share and easier for caches and analytics.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 11 lines
add_action( 'template_redirect', function (): void {
	if ( ! is_search() || ! isset( $_GET['s'] ) || isset( $_GET['post_type'] ) ) {
		return;
	}
	$term = get_search_query( false );
	if ( '' === $term ) {
		return;
	}
	wp_safe_redirect( home_url( '/search/' . rawurlencode( $term ) . '/' ) );
	exit;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WordPress search results live at /?s=your+search. WordPress also understands /search/your-search/, which looks cleaner, can be cached by CDNs that ignore query strings, and is easier to read in analytics.

How it works

When a search arrives with ?s=, the snippet redirects to the pretty version with the search term URL-encoded. WordPress already handles the /search/ path with pretty permalinks, so no rewrite rules are needed.

Searches with a post_type parameter, like WooCommerce’s product search, are left alone so their filters keep working.

Things to watch

  • This needs pretty permalinks (any setting other than “Plain”).
  • If your site’s search base has been translated, WordPress uses that word instead of “search”.
  • The redirect adds one extra request per search; search pages are rarely cached anyway.

How to test it

Search for “hello world” with your theme’s search box. The address should become /search/hello%20world/ and show results.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only