transitions = $transitions; $this->workflow = $workflow; } /** * Register hooks. * * @return void */ public function register_hooks() { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Register the transition route. * * @return void */ public function register_routes() { register_rest_route( self::NAMESPACE_V1, '/transition', array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'transition' ), 'permission_callback' => array( $this, 'can_transition' ), 'args' => array( 'post' => array( 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', ), 'action' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_key', ), 'note' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field', ), ), ) ); } /** * Permission: the user must be able to edit the target post. * * @param \WP_REST_Request $request Request. * @return bool */ public function can_transition( $request ) { return current_user_can( 'edit_post', (int) $request['post'] ); } /** * Handle the transition and return the new state. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function transition( $request ) { $post_id = (int) $request['post']; $result = $this->transitions->handle( $post_id, (string) $request['action'], (string) $request['note'] ); if ( is_wp_error( $result ) ) { return $result; } $post = get_post( $post_id ); $workflow = $this->workflow->for_post( $post ); return rest_ensure_response( array( 'status' => $result, 'status_label' => $workflow ? $this->workflow->status_label( $workflow, $result ) : $result, 'actions' => array_values( $this->workflow->allowed_actions( $post ) ), ) ); } }