Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.
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
1  
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
add comment

2 Answers

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.

<?php

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
add comment

@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

endwhile;

else :

// no search results run a new query with WP_Query

endif;
share|improve this answer
add comment

Your Answer

 
discard

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.