renderer = new Renderer(); } /** * Setup REST endpoints for the feature. */ public function setup_endpoints() { register_rest_route( 'elasticpress/v1', 'facets/taxonomies', [ 'methods' => 'GET', 'permission_callback' => [ $this, 'check_facets_taxonomies_rest_permission' ], 'callback' => [ $this, 'get_rest_facetable_taxonomies' ], ] ); register_rest_route( 'elasticpress/v1', 'facets/block-preview', [ 'methods' => 'GET', 'permission_callback' => [ $this, 'check_facets_taxonomies_rest_permission' ], 'callback' => [ $this, 'render_block_preview' ], 'args' => [ 'facet' => [ 'sanitize_callback' => 'sanitize_text_field', ], 'orderby' => [ 'sanitize_callback' => 'sanitize_text_field', ], 'order' => [ 'sanitize_callback' => 'sanitize_text_field', ], ], ] ); } /** * Check permissions of the /facets/taxonomies REST endpoint. * * @return WP_Error|true */ public function check_facets_taxonomies_rest_permission() { if ( ! is_user_logged_in() ) { return new \WP_Error( 'ep_rest_forbidden', esc_html__( 'Sorry, you cannot view this resource.', 'elasticpress' ), array( 'status' => 401 ) ); } return true; } /** * Return an array of taxonomies, their name, plural label, and a sample of terms. * * @return array */ public function get_rest_facetable_taxonomies() { $taxonomies_raw = Features::factory()->get_registered_feature( 'facets' )->get_facetable_taxonomies(); $taxonomies = []; foreach ( $taxonomies_raw as $slug => $taxonomy ) { $terms_sample = get_terms( [ 'taxonomy' => $slug, 'number' => 20, ] ); if ( is_array( $terms_sample ) ) { // This way we make sure it will be an array in the outputted JSON. $terms_sample = array_values( $terms_sample ); } else { $terms_sample = []; } $taxonomies[ $slug ] = [ 'label' => $taxonomy->label, 'plural' => $taxonomy->labels->name, 'terms' => $terms_sample, ]; } return $taxonomies; } /** * Register the block. */ public function register_block() { register_block_type_from_metadata( EP_PATH . 'assets/js/blocks/facets', [ 'render_callback' => [ $this, 'render_block' ], ] ); } /** * Render the block. * * @param array $attributes Block attributes. */ public function render_block( $attributes ) { $attributes = $this->parse_attributes( $attributes ); ob_start(); ?>