Search all meta keys matching a pattern

By default, ElasticPress indexes all public metadata. However, in order to search through a number of fields in your index (perhaps all associated with a particular plugin), you may find it easier to add these fields programmatically. Luckily, you can easily add all metadata matching a particular pattern to your search query, using the ep_weighting_configuration_for_search filter.

The following example searches all metadata containing _wysiwyg_ somewhere in the meta key:

PHP
add_filter(
	'ep_weighting_configuration_for_search',
	function( $weighting_config ) {
		global $wpdb;
		$post_meta = get_transient( 'custom_ep_distinct_post_meta' );

		if ( ! $post_meta ) {
			$post_meta = $wpdb->get_col(
				"SELECT DISTINCT meta_key
				FROM {$wpdb->postmeta} pm 
				LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID
				WHERE meta_key like '%_wysiwyg_%'"
			);

			set_transient( 'custom_ep_distinct_post_meta', $post_meta );
		}

		foreach ( $weighting_config as $post_type => $fields ) {
			foreach ( $post_meta as $meta_key ) {
				$weighting_config[ $post_type ][ "meta.{$meta_key}.value" ] = [
					'enabled' => 1,
					'weight'  => 10,
				];
			}
		}
		return $weighting_config;
	}
);

add_action(
	'update_postmeta',
	function( $meta_id, $object_id, $meta_key ) {
		if ( preg_match( '/_wysiwyg_(.*)/', $meta_key ) ) {
			delete_transient( 'custom_ep_distinct_post_meta' );
		}
	},
	10,
	3
);

In this example, each metadata field added is given a weight of 10. This corresponds to setting a  value of 10 in the Weighting Engine, meaning any matches within these fields will be boosted as well.

The update_postmeta action ensures that we clear out the transient storing the names of all matching meta keys whenever we update post meta containing the _wysiwyg_ string, which allows us to refresh the list of meta keys, adding or removing any that no longer match the SQL query. Once we perform the query, the new list is stored in the transient until associated post meta is updated again.