Sarathlal N

Redirect to post if search results only returns one post – WordPress

When we doing search in WordPress, it return list of all posts with in an archive template. The user can then click on the article they want to read.

If there is only one result for search, the result page is not necessary. In such conditions, simply redirecting the visitor directly to the article is make more sense.

Using a simple snippet, we can achieve this feature. Just add below function in our child theme’s function.php file.

add_action('template_redirect', 'redirect_single_post');

function redirect_single_post() {
	if (is_search()) {
	global $wp_query;
	if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
		wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
		exit;
	}
	}
}

Looking for a skilled WordPress/WooCommerce developer? I'm currently available for freelance, contract, or full-time remote opportunities! Let's create something amazing together. Send me a quick message, and I'll respond within 24 hours!

Recent Posts

  1. Automating Code Linting with GitHub Actions for WordPress Plugins
  2. Comprehensive Guide to Linting PHP, JavaScript, and CSS in WordPress Plugins Using Composer
  3. The Ultimate Guide to Indexing in Database Design
  4. Understanding 'update_meta_cache' in WordPress - When to Use It, When Not to, and Its Impact on Database Queries
  5. A Guide to Configuring JavaScript and SCSS Paths in WordPress Plugins with @wordpress/scripts

Your Questions / Comments

If you found this article interesting, found errors, or just want to discuss about it, please get in touch.