When a site search returns exactly one result, send the visitor straight to it instead of a results page with one link.
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;
} );
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.
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.
Search for a word that only appears in one post. You should land on that post instead of the results page.