
Search functionality is a must have if you’re dealing with a larger number of articles. If you are writing on a daily basis, imagine the number of articles scattered across different categories. If you publish only 3 short articles per day, there will be over a thousand different titles in your database after the first year. Now imageine yourself coming to the site for the first time while looking for something specific – you will want to search for it.
By default, WordPress will search through post titles, tags and of course the content. So, if searching for a word or a specific phrase, it will probably found dozens of posts and pages which contain the query. But what if there was only one search result?
If someone was searching for a very specific phrase or an entire sentence, chances are there will be only few or maybe only one result. If there is only one result found, redirecting a user to the search results page is quite unnecessary. Instead, why wouldn’t you take that user directly to the post/page found in the result?
Let’s see how to do that:
- Open functions.php
- Copy this code and paste it at the end of the file:
- Save changes
add_action(‘template_redirect’, ‘redirect_search_result);
function redirect_search_result() {
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;
}
}
}
You have prepared your WordPress for new functionality. After you have saved changes, every time a user searches for something which will return only one results, that user will be redirected directly to the post/page.
Even if it seems like nothing much, we’re sure your visitors will like you for saving them a click of button. Saving a click here and a click there will result in a better user experience and that’s probably something you want on your website, isn’t it?