Extend Search to Include Custom Fields without Plugin

By default, WordPress comes with a handy search but it only search in post titles and contents. If you are working on a custom post type, you most probably using custom fields to store its attributes. For example, A Property custom post type would have address, city and state custom fields. You may have used WP_Query object with meta_query setup, But, it does not work. If you do not use “s” attribute, it will overwrite the default search and If you use it, it will not return the expected results. This snippet will use posts_clauses filter to inject the meta query that will combine with the WordPress’s default search parameter.


function custom_search_where($pieces) {
    // filter to select search query
    if (is_search() && !is_admin()) {
        global $wpdb;
        $custom_fields = array('field1','field2');
        $keywords = explode(' ', get_query_var('s'));
        $query = "";
        foreach ($custom_fields as $field) {
             foreach ($keywords as $word) {
                 $query .= "((mypm1.meta_key = '".$field."')";
                 $query .= " AND (mypm1.meta_value  LIKE '%{$word}%')) OR ";
        if (!empty($query)) {
            // add to where clause
            $pieces['where'] = str_replace("(((wp_posts.post_title LIKE '%", "( {$query} ((wp_posts.post_title LIKE '%", $pieces['where']);
            $pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} AS mypm1 ON ({$wpdb->posts}.ID = mypm1.post_id)";
    return ($pieces);
add_filter('posts_clauses', 'custom_search_where', 20, 1);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s