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.

  • 1
    not sure I understand the question- how are you to know nothing was found if you haven't queried yet?
    – Milo
    May 17, 2012 at 16:06

2 Answers 2


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;

@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


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.