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.


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("((({$wpdb->posts}.post_title LIKE '%", "( {$query} (({$wpdb->posts}.post_title LIKE '%", $pieces['where']);

            $pieces['join'] = $pieces['join'] . " INNER JOIN {$wpdb->postmeta} AS mypm1 ON ({$wpdb->posts}.ID = mypm1.post_id)";
            $pieces[‘groupby’] = “{$wpdb->posts}.ID”;
    return ($pieces);
add_filter('posts_clauses', 'custom_search_where', 20, 1);

3 Responses to Snippet: Extend Search to Include Custom Fields without Plugin

  1. Thib says:


    nice tip thank you.

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

  2. 3pepe3 says:

    There is a problem in the snip. If keyword is found in several fields then the page will show the post several times.
    |__f1 : 456485
    |__f2 : 4694848
    |__f3 : 48

    Searching in the keyword “48” then in the search page I will have 3 times Foobar_Post while I just need to be shown 1 time.

    To fix this you should add

    // add groupby
    $pieces[‘groupby’] = “{$wpdb->posts}.ID”;

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>