WP Snippet: Include custom post meta in WordPress search

Following this article i think is a litte old, here i bring an improved code.

This function allows include any post_meta in search query.

Advertisements

18 thoughts on “WP Snippet: Include custom post meta in WordPress search

  1. if( !defined( ‘ABSPATH’ ) )
    exit;

    function modify_wp_search_where( $where ) {

    if( is_search() ) {
    
        global $wpdb, $wp;
    
        $where = preg_replace(
            "/($wpdb->posts.post_title (LIKE '%{$wp->query_vars['s']}%'))/i",
            "$0 OR ( $wpdb->postmeta.meta_value LIKE '%{$wp->query_vars['s']}%' )",
            $where
            );
    
        add_filter( 'posts_join_request', 'modify_wp_search_join' );
        add_filter( 'posts_distinct_request', 'modify_wp_search_distinct' );
    }
    
    return $where;
    

    }
    add_action( ‘posts_where_request’, ‘modify_wp_search_where’ );

    function modify_wp_search_join( $join ) {

    global $wpdb;
    
    return $join .= " LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
    

    }

    function modify_wp_search_distinct( $distinct ) {

    return 'DISTINCT';
    

    } try this it is functional just add in your function.php .. hope this help

  2. Hi, i have a custom post type called properties, and a custom field called operation_select, when i do a search, doesn’t work, the code is:

    function custom_search_query_one( $query ) {
    if ( !is_admin() && $query->is_search ) {
    $query->set(‘meta_query’, array(
    array(
    ‘key’ => ‘operation_select’,
    ‘value’ => $query->query_vars[‘s’],
    ‘compare’ => ‘LIKE’
    )
    ));
    $query->set(‘properties’, ‘post’);
    };
    }
    add_filter( ‘pre_get_posts’, ‘custom_search_query_one’);

    any idea?, thanks.

    • try

      function custom_search_query_one( $query ) {
      if ( !is_admin() && $query->is_search ) {
      $value = $query->query_vars[‘s’];
      $query->query_vars[‘s’] = “”;
      $query->set(‘meta_query’, array(
      array(
      ‘key’ => ‘operation_select’,
      ‘value’ => $value,
      ‘compare’ => ‘LIKE’
      )
      ));
      $query->set(‘properties’, ‘post’);
      };
      }

      thats is, cleaning the value of the “s” variable…

      I had a similar problem and it helped me… i hope is the same case 🙂

  3. just one more thing… it takes quite long to search the elements (and i just have 5 testing samples… ) any idea of how i could optimize it? thanks in advance

  4. Love you Gaggo, you made it work… i was trying the option above and got nothing… THANK YOU VERY MUCH!!

  5. gaggo, you are awesome, thank you very much for your code, I spent days looking for your solution – thanks!

  6. @Thomas: I think your search didn’t work because the “s” parameter is overwriting your meta search. Try it with my code.

  7. Hi there, I did the same with the meta_query functionality:

    function custom_search_query( $query ) {
    $custom_fields = array(
    // put all the meta fields you want to search for here
    "_post_title",
    "text_english",
    "text_deutsch"
    );
    $searchterm = $query->query_vars['s'];
    // we have to remove the "s" parameter from the query, because it will prevent the posts from being found
    $query->query_vars['s'] = "";
    if ($searchterm != "") {
    $meta_query = array('relation' => 'OR');
    foreach($custom_fields as $cf) {
    array_push($meta_query, array(
    'key' => $cf,
    'value' => $searchterm,
    'compare' => 'LIKE'
    ));
    }
    $query->set("meta_query", $meta_query);
    };
    }
    add_filter( "pre_get_posts", "custom_search_query");
    add_action( "save_post", "add_title_custom_field");
    
    function add_title_custom_field($postid){
    // since we removed the "s" from the search query, we want to create a custom field for every post_title. I don't use post_content, if you also want to index this, you will have to add this also as meta field.
    update_post_meta($postid, "_post_title", $_POST["post_title"]);
    }
    
    • A couple questions:

      Any idea how to put the “s” param back so the UI looks nice?
      Also this code seems to break searches on titles and post content, is there a way to make it more intelligent?

  8. Nope she don\\’t work man…. Why I don\\’t know….. The query is modified as I have print_r to the screen $query in the function above and the $where from upon the \\’post_where_request\\’. I\\’m stumped. It puts in the query but then the query doesn\\’t seem to work. Arg.

    – AND ( (wp_postmeta.meta_key = \\’address\\’ AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \\’%12345%\\’) –

    I do not know SQL very well at all but could it have something to do with the CAST and AS CHAR?

    • Hello Tommas,

      you don’t need return $wp_query because, we’re using “->set” method, that includes the changes in query.
      For later versions of 3.1, this should work… maybee you are doing something wrong…
      Can you put your code?

    • Remember replace ‘__meta_key__’ for your meta name
      and comment this line (that it is an example):
      // $query->set('post_type', 'project'); // adicionalmente podemos añadir más condicionales

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