0

I want empty search returns to home page in my wordpress . how i can do this . im trying to using javascript and html tags , but te are not too fast . if no result user returns to home page not to nothing found page.

0

This will do exactly what you're asking for:

add_action('wp', 'redirect_empty_search');
function redirect_empty_search() {
  global $wp_query;
  if( isset( $_REQUEST['s'] ) && 0 === $wp_query->post_count ) {
    wp_redirect( home_url() );
    exit;
  }
}

You'll want to add some kind of message on the homepage when this happens, maybe by adding a query parameter to home_url() and displaying a message in your theme when that parameter is set. Something like:

wp_redirect( add_query_arg( 'searchfailed', '1', home_url() ) );
  • I was in the process of considering to suggest the same approach, but of course that isn't using javascript - and you just have been faster. I'd do it a little bit different, having the if condition like this: isset($_GET['s']) && $_GET['s']=='' - no need for the global this way. – Nicolai Sep 5 '13 at 15:17
  • 1
    You know...I wonder if we hit a language barrier here. Your way is definitely much better for detecting empty searches (i.e. nothing in the search box). Mine is for empty search results. Some clarification from the original poster would be really helpful. I think between the two of us, we have the perfect answer all ready to go. – Dave Ross Sep 5 '13 at 15:27
  • You might be right about the language barrier. And you additional explanation is right on spot. I should have thought of writting that.. :D – Nicolai Sep 5 '13 at 15:35
  • @DaveRoss exactly what I wanted. Thanks a lot for your help. – gagan Sep 5 '13 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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