forked from MESH-Research/elasticpress-buddypress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelasticpress-rest.php
87 lines (70 loc) · 1.8 KB
/
elasticpress-rest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
* Plugin Name: ElasticPress REST
* Version: alpha
* Description: ElasticPress custom feature to support live filtering via a custom WordPress REST API endpoint.
*/
class EPR_REST_Posts_Controller extends WP_REST_Controller {
// include debug output in REST response
const DEBUG = false;
/**
* Constructor.
*
* @since alpha
* @access public
*/
public function __construct() {
$this->namespace = 'epr/v1';
$this->rest_base = '/query';
// this is not necessary and can cause bad results from elasticsearch, disable it.
remove_filter( 'request', 'bbp_request', 10 );
}
/**
* Registers the routes for the objects of the controller.
*
* @since alpha
* @access public
*
* @see register_rest_route()
*/
public function register_routes() {
register_rest_route( $this->namespace, $this->rest_base, [
'methods' => 'GET',
'callback' => [ $this, 'get_items' ],
] );
}
/**
* Query ElasticPress using query vars
*
* @return WP_REST_Response
*/
public function get_items( $data ) {
global $wp_query;
$response = new WP_REST_Response;
$debug = [];
$response_data = [ 'posts' => [] ];
add_action( 'ep_add_query_log', function( $ep_query ) use ( &$response, &$debug ) {
$debug['ep_query'] = $ep_query;
$response->set_status( $ep_query['request']['response']['code'] );
} );
$wp_query->query( array_merge(
[ 'ep_integrate' => true ],
$data->get_query_params()
) );
$debug['wp_query'] = $wp_query;
if ( have_posts() ) {
while ( have_posts() ) {
ob_start();
the_post();
get_template_part( 'content', get_post_format() );
$response_data['posts'][] = ob_get_contents();
ob_end_clean();
}
}
if ( self::DEBUG ) {
$response_data['debug'] = $debug;
}
$response->set_data( $response_data );
return $response;
}
}