Describe your question
I have installed the ElasticPress plugin in one of my Wordpress sites that makes a heavy use of WP_Query. The type of WP_Query that we make involves searching data in Custom Post Fields of Custom Post Types. On the plugin page: page=elasticpress-weighting I see that it is only possible to index and weight content based on: Title, Content, Excerpt or Author.
Is there a way to make "Custom Post Fields" searchables and weightables?
Hi @alexgarciab ,
You can use the ep_weighting_fields_for_post_type filter for this. For example, to add a meta field with my_custom_field as the key, your code would look like this:
add_filter(
'ep_weighting_fields_for_post_type',
function( $fields, $post_type ) {
if ( 'post' === $post_type ) {
if ( empty( $fields['meta'] ) ) {
$fields['meta'] = array(
'label' => 'Custom Fields',
'children' => array(),
);
}
$key = 'meta.my_custom_field.value'; // Change my_custom_field here to what you need.
$fields['meta']['children'][ $key ] = array(
'key' => $key,
'label' => 'My Custom Field',
);
}
return $fields;
},
10,
2
);
With that in place, you'll have this new element in the Manage Search Fields & Weighting Screen, under "Posts":

You'll need then to enable it as "Searchable" and adjust the Weight.
Please let us know if it helped and/or if you have any further questions, okay?
Thanks!
I'm closing this issue, as the question was answered. Please feel free to reopen it if needed. Also, this subject was also explored in more depth in this blog post: https://www.elasticpress.io/blog/2020/06/custom-fields-and-weighted-search-with-elasticpress-part-2/ :)
Thanks!
Most helpful comment
Hi @alexgarciab ,
You can use the ep_weighting_fields_for_post_type filter for this. For example, to add a meta field with
my_custom_fieldas the key, your code would look like this:With that in place, you'll have this new element in the
Manage Search Fields & WeightingScreen, under "Posts":You'll need then to enable it as "Searchable" and adjust the Weight.
Please let us know if it helped and/or if you have any further questions, okay?
Thanks!