Auto-Redirect when WordPress Search Query Only Returns One Match

There are occasions when looking a WordPress weblog, you solely get one merchandise within the consequence. Relying on how organized your web site is, this must be the merchandise the person was in search of in any case. One among our customers requested if there was a technique to redirect to the submit if the search question outcomes just one match. On this article, we’re going to present you the way to redirect customers to the submit when the search question solely returns one match.

All it’s a must to do is open your theme’s capabilities.php file and paste the next snippet.

1
2
3
4
5
6
7
8
9
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 ) );
        }
    }
}

Now you need to beware that some customers is not going to anticipate this performance. So it could freak them out.

You May Also Like : How to Add an Admin User to the WordPress Database via MySQL

If you liked this article, make sure to hit the bell for getting our latest updates and share this article with your friends in every social media platforms.

1 thought on “Auto-Redirect when WordPress Search Query Only Returns One Match”

  1. Pingback: Add a Custom Class in WordPress Menu Item using Conditional...

Leave a Comment

Your email address will not be published. Required fields are marked *