Snippet: 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.

Snippet

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

One Response to Snippet: Extend Search to Include Custom Fields without Plugin

  1. Thib says:

    Hi,

    nice tip thank you.

    It would be better to $wpdb->prefix instead of “wp_” because it doesn’t work in mutlisite installation

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>