Redirect single search result in WordPress

/**
 * Redirects single search result.
 *
 * @see https://wpcodebook.com/wordpress-redirect-single-search-result/
 */
add_action( 'template_redirect', function () {
	if ( 
		is_search() && 
		is_main_query() 
	) {
		global $wp_query;
		if ( 
			1 === $wp_query->post_count && 
			1 === $wp_query->max_num_pages 
		) {
			$url = get_permalink( $wp_query->posts['0']->ID );
			wp_redirect( $url );
			exit;
		}
	}
} );

Leave a Comment