How to integrate ElasticPress with AJAX requests

As AJAX requests in WordPress are executed in an admin context (it is located at wp-admin/admin-ajax.php after all), some custom code is required to fully integrate your queries with ElasticPress.

First, adding 'ep_integrate' => true to your WP_Query arguments will not be enough. That only serves to integrate queries that wouldn’t be regularly integrated, like a query that is not a search.

The first filter you must use is ep_ajax_wp_query_integration: passing true to that will make ElasticPress integrate with queries run in AJAX contexts.

Also, to have your weighting configuration applied to those queries, you need to pass true to the ep_enable_do_weighting filter.

This snippet is an example of how to use all those filters:

PHP
function ajax_request_example() {
	...
	// Add this to enable EP integration with AJAX requests
	add_filter( 'ep_ajax_wp_query_integration', '__return_true' );

	// Add this to apply the weighting fields configuration to your queries
	add_filter( 'ep_enable_do_weighting', '__return_true' );

	$query1 = new \WP_Query(
		[
			...
			's' = 'post',
			...
		]
	);
	...
	$query2 = new \WP_Query(
		[
			...
			'post_type'    = 'post',
			'ep_integrate' = true, // This is only needed if the query is not a search
			...
		]
	);
	...
}
add_action( 'wp_ajax_custom_ajax_action', 'ajax_request_example' );
add_action( 'wp_ajax_nopriv_custom_ajax_action', 'ajax_request_example' );

If you need to debug queries sent in AJAX context, check our Using the ElasticPress Debugging Add-On Plugin article.