0

I'm looking for a way to modify the search query if the performed query returned no results.

Let's say I'm looking for "Opening times", so I go to this URL:

http://mysite.com?s=Opening+times

Now, in my search.php I want to check if that query gave no results, and in that case, I want to perform a new query with a different term, wihtout any required action by the user.

Something like this:

global $wp_query;

$total_results = $wp_query->found_posts;

if ( $total_results == 0 ) {
    // Create a new query with the terms 'Find Us'
}

// Display results (either those for the 'Opening times' query or for the 'Find Us' one if the former didn't return any result)

Is there an easy way to do this?

2 Answers 2

3

You should create a custom query inside if.

if ( $total_results == 0 ) {
    // Create a new query with the terms 'Find Us'

$query = new Wp_query('s=Find Us');
   if ($query->have_posts()):
                while ($query->have_posts()):$query->the_post();
                //whatever you want to do with the result
                endwhile;
            endif;
       wp_reset_postdata();
}

You can refer Creating a search page and Wp_query class referrence for more detail.

0
0

Modify the code in your header template file:

if (is_search() && !have_posts())
{
   header('Location: http://mysite.com?s=Find+us');
   exit;
}

Just make sure that your redirected query always has results, or else you'll have to do something else to avoid being in an endless redirection loop.

If you just want to handle it in the search.php template page itself, read the multiple loops section of the Wordpress docs that describe The Loop. They show a number of different ways to handle multiple queries in a single page.

1
  • It's not bad, but I prefer MortalViews' answer, because it gives me more control, for example, I can try may other queries and return the results of the one that gives more results or things like that... thanks anyway!
    – MikO
    Commented May 23, 2014 at 11:25

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.