WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
function hotlinkers_wp_query($query) {

     if ( !$query->is_admin && $query->is_search) {
            $search_query = str_replace('-',' ', $query->query_vars['s']);
            $query->set('s', $search_query);

     return $query;
add_action('pre_get_posts', 'hotlinkers_wp_query');

this is for the search results found, on search.php i have an else, so if no searches are found it shows 15 random posts (using wp query)

wanted to avoid that if possible to do via pre_get_posts.

share|improve this question
not sure I understand the question- how are you to know nothing was found if you haven't queried yet? – Milo May 17 '12 at 16:06
up vote 2 down vote accepted

Like others have said you can't use pre get posts since there is no way of knowing if the search returned any posts. I would also say that the if else is a very clean way to do it and might be the better choice if anyone else is going to be working on this.

But if you really wanted to do it with a filter on either the posts_results or the_posts to return the replacement posts that should be shown if the search is empty.


add_filter('the_posts', 'np_replace_empty_search', 10, 2);
function np_replace_empty_search($posts, $wp_query){
    if($wp_query->is_search && empty($posts)){
        $new_query = new WP_Query();

        return $new_query->posts;
    return $posts;
share|improve this answer

@Milo is right. You can't use pre_get_posts to determine the number of results because pre_get_posts modifies a query before it's run (which is why it's so great, just not for this use).

I can't think of a great way to do this using a filter. Your normal loop is really what you want:

if( have_posts() ) : while( have_posts() ) : the_post();

// do stuff


else :

// no search results run a new query with WP_Query

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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