I have a a CPT set up with a custom taxonomy attached to it. I recently noticed that if I search for 0 (zero), in the back-end as well as the front-end, it gives me results. None of these resultant posts have 0 anywhere in the title as well as the content. I have not modified the loop in anyway, it is just the plain search template. This makes me wonder about 2 things:

  1. What does WP search through by default?
  2. Is there a way to stop it from searching for 0?

Any ideas?

Update:

From the comments below, I am updating my requirement:

Is there a way to search for the posts which contain 0 in either the title or the content, when 0 is entered as the search key?

1
1

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);
    }
}

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *