Content & Posts PHP Beginner

Go Straight to the Post When Search Finds One Result

When a site search returns exactly one result, send the visitor straight to it instead of a results page with one link.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 10 lines
add_action( 'template_redirect', function (): void {
	global $wp_query;

	if ( ! is_search() || is_paged() || 1 !== (int) $wp_query->found_posts ) {
		return;
	}

	wp_safe_redirect( get_permalink( $wp_query->posts[0] ), 302 );
	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.

A search results page with a single result is an extra click for no reason. This snippet takes the visitor straight to the post or page they were looking for.

How it works

template_redirect runs after WordPress has run the search but before the results template loads. If the main query is a search with exactly one match, the snippet redirects to that post’s permalink with a temporary 302 redirect.

Things to watch

  • Use 302, not 301. The same search could return more results tomorrow.
  • Your analytics will record fewer search result page views, because those visits now land on the post.

How to test it

Search for a word that only appears in one post. You should land on that post instead of the results page.

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