phpwordpresselasticsearchadvanced-custom-fieldssearchly

ElasticPress - searching meta and Advanced Custom Fields not working


We are using Wordpress 4.9.5 with ElasticPress 2.5 and Searchly.

The default search works fine. However, we are indexing hundreds of thousands of part numbers, each of which are a post in wordpress. Like many part numbers, they have titles like ABC-12-B23-QQ.

We are using ElasticPress right out of the box. It's advertised as working great right out of the box, but ...

It appears that it's only searching the post titles. It is not searching our Advanced Custom Fields at all. We are using ACF for all of the part details, like length, color, and finish, so it is very important that we be able to search these fields.

How do I get Elasticpress to search my custom fields? Do I need to use custom mapping?

https://github.com/10up/ElasticPress

NOTE: I am posting this so it is included on stackoverflow for the benefit of others who search later. It would have saved me hours if I would have found this on Stackoverflow at the beginning of my search. :)


Solution

  • It turns out that yes, ElasticPress does map all the meta fields automatically, but by default, it does not search them.

    According to the documentation (https://github.com/10up/ElasticPress),

    "The following are special parameters that are only supported by ElasticPress.

    search_fields (array)
    If not specified, defaults to array( 'post_title', 'post_excerpt', 'post_content' ).
    

    This was my problem. To solve, you must tell ElasticPress what fields to search.

    The ElasticPress documentation includes this example using WP_Query:

    new WP_Query( array(
        's'             => 'meta search phrase',
        'search_fields' => array(
            'post_title',
            'post_content',
            'post_excerpt',
            'meta' => array( 'meta_key_1', 'meta_key_2' ),
        ),
    ) );
    

    I was really needing to hook into the existing search query, so here is an example of what I did using the pre_get_posts action:

    function my_search_filter($query) {
      if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search() ) {
            $query->set('search_fields', array(
            'post_title',
            'meta' => array( 'bin_part_number',
                            'shelf_part_number',
                            )));
        }
      }
    }
    add_action('pre_get_posts','my_search_filter',1);