A search for ‘0’ returns results

Considering @Mayeenul Islam comment:

I’ve just tested in a blank theme with dummy data, search with 0
(zero) fired an empty search – that means all:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts WHERE 1=1 AND
wp_posts.post_type IN ('post', 'page', 'attachment') AND
(wp_posts.post_status="publish") ORDER BY wp_posts.post_date DESC
LIMIT 0, 10

and the fact that wp-includes/query.php contains

if ( ! empty( $q['s'] ) ) {
    $search = $this->parse_search( $q );
}

, we can see that !empty($q['s']), where $q['s'] == 0 (or "0") will return FALSE. This means that search query wont have LIKE part, when $q['s'] == 0 and it return “all” posts since nothing restrict query with specific conditions, that should be inside LIKE part.

This is confirmed by empty() function documentation:

The following things are considered to be empty:

  • 0 (0 as an integer)
  • “0” (0 as a string)

Due to that we’re not able to filter/update, “0” in order to pass if-empty conditional logic. What I suggest is a query updates in case if users are going to search for “0”.

Here is a quickfix how to allow users to search for “0”.

add_filter("posts_where", "search_hotfix", 10, 1);
function search_hotfix($where_clause){

    if(get_query_var('s') == 0){
      $where_clause .=  " AND (((wp_posts.post_title LIKE '%0%') OR (wp_posts.post_content LIKE '%0%'))) ";
    }

    return $where_clause; 
}

UPDATE:

And here is a quickfix how to stop WP search for “0”. This code will force WP_Query to provide no results.

add_action('pre_get_posts', 'search_hotfix_reset_q');
function search_hotfix_reset_q($query){
    if ( get_query_var('s') == 0) {
        $query->query_vars['post__in'] = array(0);
    }
}

Leave a Comment