Altug Gurkaynak
Posted on January 6, 2023
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
Posted on January 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.