wordpress pro tip open the only result automatically

WordPress Pro Tip: Open The Single Search Result Automatically

From the perspective of User Experience Design (or UXD in short) we have to put ourselves in the user’s shoes. While doing that, as a designer, I clear my mind from the experience and thoughts I had while creating the product to be have first hand users mind set.

When I did so, I found out that a single item on a search result is pointless. If there is only one result on a search, why bother or lose time viewing it?

On the previous WordPress tip, we talked about limiting the search categories. This time we are taking one more step forward to check if there is only 1 post.

It’s time to write our code

We create a new function in functions.php :

add_action('template_redirect', 'one_match_redirect');
function one_match_redirect() {
	if (is_search()) {
		global $wp_query;
		if ($wp_query->post_count == 1) {
			wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );

This is everything. From now on, if your search ends with a single result query, your WordPress site will automatically open that single result.

For detailed information about the wp_redirect we use here: developer.wordpress.org/reference/hooks/wp_redirect


WordPress Tip: Limiting the Search to a Single Category