Search Query

WordPress Search Query

Search Query

Advertisements

Here are instances when a WordPress blog search returns just one item. This might be the thing the user was seeking for anyhow, depending on how well organized your site is. When a search query returns only one match, one of our users enquired as to whether there was a method to redirect to the post. We’ll teach you how to send people to the content when a search only finds up one match in this article.

 

Advertisements

Simply open the functions.php file for your theme and paste the following code.

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 ) );
        }
    }
}

Be aware that not all users will be expecting this functionality. So they might be terrified.

Advertisements

Leave a Reply