\WP_REST_Server::READABLE, 'callback' => array( $this, 'get_grid' ), 'permission_callback' => array( $this, 'permissions_check' ), 'args' => array( 'page' => array( 'description' => __( 'Page of posts to return.', 'mm-post-grid' ), 'type' => 'integer', 'default' => 2, 'minimum' => 1, 'maximum' => 500, 'sanitize_callback' => 'absint', ), 'grid' => array( 'description' => __( 'JSON encoded grid arguments.', 'mm-post-grid' ), 'type' => 'string', 'required' => true, 'validate_callback' => array( $this, 'validate_payload' ), ), ), ) ); } /** * Read only route for public, published content. * * @since 0.1 * @return bool */ public function permissions_check() { return true; } /** * Rejects payloads that are too large to be a grid. * * @since 0.1 * * @param mixed $value Raw parameter value. * @return bool */ public function validate_payload( $value ) { return is_string( $value ) && '' !== $value && strlen( $value ) <= self::MAX_PAYLOAD; } /** * Returns the cards of the requested page. * * @since 0.1 * * @param \WP_REST_Request $request Request object. * @return \WP_REST_Response|\WP_Error */ public function get_grid( \WP_REST_Request $request ) { $payload = json_decode( (string) $request->get_param( 'grid' ), true, 8 ); if ( ! is_array( $payload ) ) { return new \WP_Error( 'mmpg_invalid_payload', __( 'The grid arguments could not be read.', 'mm-post-grid' ), array( 'status' => 400 ) ); } $args = Args::from_request( $payload ); $page = max( 1, (int) $request->get_param( 'page' ) ); $query = Query_Builder::query( $args, $page ); $max_pages = Query_Builder::max_pages( $query, $args ); if ( $page > $max_pages ) { return new \WP_REST_Response( array( 'html' => '', 'page' => $page, 'max_pages' => $max_pages, 'has_more' => false, 'count' => 0, ), 200 ); } return new \WP_REST_Response( array( 'html' => wp_kses( Renderer::cards( $query, $args ), Renderer::allowed_html() ), 'page' => $page, 'max_pages' => $max_pages, 'has_more' => $page < $max_pages, 'count' => (int) $query->post_count, ), 200 ); } }