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 ) );
}
}
}
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
Top comments (1)
you should
exit
ordie
after redirect.