WordPress Pro Tip: Open The Single Search Result Automatically

altugdesign

Altug Gurkaynak

Posted on January 6, 2023

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 displaying a single item on a search result is pointless.
๐Ÿ‘‰ If there is only 1 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 :

// IF THE SEARCH HAS ONE RESULT, AUTOMATICALLY OPEN THAT RESULT
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 ) );
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
altugdesign
Altug Gurkaynak

Posted on January 6, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About