| 1 |
<?php |
| 2 |
/** |
| 3 |
* Taxonomies REST API Controller |
| 4 |
* |
| 5 |
* @since 5.0.0 |
| 6 |
* @package elasticpress |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace ElasticPress\REST; |
| 10 |
|
| 11 |
use ElasticPress\Features; |
| 12 |
|
| 13 |
/** |
| 14 |
* Taxonomies API controller class. |
| 15 |
* |
| 16 |
* @since 5.0.0 |
| 17 |
* @package elasticpress |
| 18 |
*/ |
| 19 |
class Taxonomies { |
| 20 |
|
| 21 |
/** |
| 22 |
* Register routes. |
| 23 |
* |
| 24 |
* Registers the route using its own endpoint and the previous facets |
| 25 |
* endpoint, for backwards compatibility. |
| 26 |
* |
| 27 |
* @return void |
| 28 |
*/ |
| 29 |
public function register_routes() { |
| 30 |
$args = [ |
| 31 |
'callback' => [ $this, 'get_taxonomies' ], |
| 32 |
'methods' => 'GET', |
| 33 |
'permission_callback' => [ $this, 'check_permission' ], |
| 34 |
]; |
| 35 |
|
| 36 |
register_rest_route( 'elasticpress/v1', 'taxonomies', $args ); |
| 37 |
register_rest_route( 'elasticpress/v1', 'facets/taxonomies', $args ); |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Check that the request has permission. |
| 42 |
* |
| 43 |
* @return boolean |
| 44 |
*/ |
| 45 |
public function check_permission() { |
| 46 |
return current_user_can( 'edit_theme_options' ); |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Get filterable taxonomies. |
| 51 |
* |
| 52 |
* @param \WP_REST_Request $request Full details about the request. |
| 53 |
* @return array |
| 54 |
*/ |
| 55 |
public function get_taxonomies( \WP_REST_Request $request ) { |
| 56 |
$filterable_taxonomies = Features::factory()->get_registered_feature( 'facets' )->types['taxonomy']->get_facetable_taxonomies(); |
| 57 |
|
| 58 |
$taxonomies = []; |
| 59 |
|
| 60 |
foreach ( $filterable_taxonomies as $slug => $taxonomy ) { |
| 61 |
$terms_sample = get_terms( |
| 62 |
[ |
| 63 |
'taxonomy' => $slug, |
| 64 |
'number' => 20, |
| 65 |
] |
| 66 |
); |
| 67 |
if ( is_array( $terms_sample ) ) { |
| 68 |
// This way we make sure it will be an array in the outputted JSON. |
| 69 |
$terms_sample = array_values( $terms_sample ); |
| 70 |
} else { |
| 71 |
$terms_sample = []; |
| 72 |
} |
| 73 |
|
| 74 |
$taxonomies[ $slug ] = [ |
| 75 |
'label' => $taxonomy->labels->singular_name, |
| 76 |
'plural' => $taxonomy->labels->name, |
| 77 |
'terms' => $terms_sample, |
| 78 |
]; |
| 79 |
} |
| 80 |
|
| 81 |
return $taxonomies; |
| 82 |
} |
| 83 |
} |
| 84 |
|