Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
WordPress Plugins
View all Guides

Auto-Redirect when WordPress Search Query Only Returns One Match

Last updated on by
Special WordPress Hosting offer for WPBeginner Readers
Auto-Redirect when WordPress Search Query Only Returns One Match

There are times when searching a WordPress blog, you only get one item in the result. Depending on how organized your site is, this should be the item the user was looking for anyways. One of our users asked if there was a way to redirect to the post if the search query results only one match. In this article, we are going to show you how to redirect users to the post when the search query only returns one match.

All you have to do is open your theme’s functions.php file and paste the following snippet.

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 must beware that some users will not expect this functionality. So it may freak them out.

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »


  1. Eric says:

    I want to make it so when some searches a specific phrase it redirects to an easter egg, like if someone searches “I see dead people” specifically it’ll redirect them to a URL I can define.

  2. Nebulas Website Design says:

    Thanks for this piece of code it made my client very happy and I didn’t thnk it could be done. However it’s not working for us we are using the Relevanssi search plugin should it work with this?

  3. carlos says:

    What if I want to redirect any search query to the most relevant post no matter what the number of posts the search returns? I’d really like to be able to do that.

  4. CalebZahnd says:

    This is handy. Thanks!

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.