I want to send visitors to my search.php after a search to display list of posts. If there is only one search result, user can directlyto the post in question(something like GOOGLE's I am Feeling Lucky Button)

Thank you all.

1 Answer 1


Add this snippet to your functions.php

function redirect_the_single_post() {
    if (is_search() && is_main_query()) {
        global $wp_query;
        if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
add_action('template_redirect', 'redirect_the_single_post' );

hope this will help you!!

  • 5
    +1 for this. You could/should, however, also check if this is the main query, so I would change the first line to this: if (is_search() && is_main_query()) {. And the permalink can also be generated from $GLOBALS['post']->ID - but that is not so much shorter. ;) But it is about retrieving a property of an element of an array. Your code is about retrieving a property of an element of an array, which is a property of another object.
    – tfrommen
    Oct 30, 2013 at 7:47
  • 1
    @AbhishekKaushik, take the point and add it to the Answer. People will be copy/pasting your snippet for years to come, better improve it, no? ;)
    – brasofilo
    Oct 30, 2013 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.