类文档

WP_REST_Block_Renderer_Controller

💡 云策文档标注

概述

WP_REST_Block_Renderer_Controller 是一个 WordPress REST API 控制器,用于提供渲染块的端点。它继承自 WP_REST_Controller,主要处理动态块的渲染请求。

关键要点

  • 提供 REST 端点以通过 block 的 render_callback 返回块输出。
  • 包含权限检查方法,确保用户有权读取块内容。
  • 注册路由时支持动态块名称,并定义请求参数如 attributes 和 post_id。
  • 使用 render_block 函数确保所有相关过滤器被应用。
  • 返回符合 JSON Schema 的输出模式。

代码示例

public function register_routes() {
    register_rest_route(
        $this->namespace,
        '/' . $this->rest_base . '/(?P<name>[a-z0-9-]+/[a-z0-9-]+)',
        array(
            'args'   => array(
                'name' => array(
                    'description' => __( 'Unique registered name for the block.' ),
                    'type'        => 'string',
                ),
            ),
            array(
                'methods'             => array( WP_REST_Server::READABLE, WP_REST_Server::CREATABLE ),
                'callback'            => array( $this, 'get_item' ),
                'permission_callback' => array( $this, 'get_item_permissions_check' ),
                'args'                => array(
                    'context'    => $this->get_context_param( array( 'default' => 'view' ) ),
                    'attributes' => array(
                        'description'       => __( 'Attributes for the block.' ),
                        'type'              => 'object',
                        'default'           => array(),
                        'validate_callback' => static function ( $value, $request ) {
                            $block = WP_Block_Type_Registry::get_instance()->get_registered( $request['name'] );

                            if ( ! $block ) {
                                return true;
                            }

                            $schema = array(
                                'type'                 => 'object',
                                'properties'           => $block->get_attributes(),
                                'additionalProperties' => false,
                            );

                            return rest_validate_value_from_schema( $value, $schema );
                        },
                        'sanitize_callback' => static function ( $value, $request ) {
                            $block = WP_Block_Type_Registry::get_instance()->get_registered( $request['name'] );

                            if ( ! $block ) {
                                return true;
                            }

                            $schema = array(
                                'type'                 => 'object',
                                'properties'           => $block->get_attributes(),
                                'additionalProperties' => false,
                            );

                            return rest_sanitize_value_from_schema( $value, $schema );
                        },
                    ),
                    'post_id'    => array(
                        'description' => __( 'ID of the post context.' ),
                        'type'        => 'integer',
                    ),
                ),
            ),
            'schema' => array( $this, 'get_public_item_schema' ),
        )
    );
}

注意事项

  • 权限检查基于 post_id:如果指定 post_id,用户需有 edit_post 权限;否则需有 edit_posts 权限。
  • 仅支持动态块(is_dynamic() 返回 true),无效块会返回 404 错误。
  • attributes 参数会根据块的注册属性进行验证和清理。

📄 原文内容

Controller which provides REST endpoint for rendering a block.

Description

See also

Methods

Name Description
WP_REST_Block_Renderer_Controller::__construct Constructs the controller.
WP_REST_Block_Renderer_Controller::get_item Returns block output from block’s registered render_callback.
WP_REST_Block_Renderer_Controller::get_item_permissions_check Checks if a given request has access to read blocks.
WP_REST_Block_Renderer_Controller::get_item_schema Retrieves block’s output schema, conforming to JSON Schema.
WP_REST_Block_Renderer_Controller::register_routes Registers the necessary REST API routes, one for each dynamic block.

Source

class WP_REST_Block_Renderer_Controller extends WP_REST_Controller {

	/**
	 * Constructs the controller.
	 *
	 * @since 5.0.0
	 */
	public function __construct() {
		$this->namespace = 'wp/v2';
		$this->rest_base = 'block-renderer';
	}

	/**
	 * Registers the necessary REST API routes, one for each dynamic block.
	 *
	 * @since 5.0.0
	 *
	 * @see register_rest_route()
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<name>[a-z0-9-]+/[a-z0-9-]+)',
			array(
				'args'   => array(
					'name' => array(
						'description' => __( 'Unique registered name for the block.' ),
						'type'        => 'string',
					),
				),
				array(
					'methods'             => array( WP_REST_Server::READABLE, WP_REST_Server::CREATABLE ),
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'get_item_permissions_check' ),
					'args'                => array(
						'context'    => $this->get_context_param( array( 'default' => 'view' ) ),
						'attributes' => array(
							'description'       => __( 'Attributes for the block.' ),
							'type'              => 'object',
							'default'           => array(),
							'validate_callback' => static function ( $value, $request ) {
								$block = WP_Block_Type_Registry::get_instance()->get_registered( $request['name'] );

								if ( ! $block ) {
									// This will get rejected in ::get_item().
									return true;
								}

								$schema = array(
									'type'                 => 'object',
									'properties'           => $block->get_attributes(),
									'additionalProperties' => false,
								);

								return rest_validate_value_from_schema( $value, $schema );
							},
							'sanitize_callback' => static function ( $value, $request ) {
								$block = WP_Block_Type_Registry::get_instance()->get_registered( $request['name'] );

								if ( ! $block ) {
									// This will get rejected in ::get_item().
									return true;
								}

								$schema = array(
									'type'                 => 'object',
									'properties'           => $block->get_attributes(),
									'additionalProperties' => false,
								);

								return rest_sanitize_value_from_schema( $value, $schema );
							},
						),
						'post_id'    => array(
							'description' => __( 'ID of the post context.' ),
							'type'        => 'integer',
						),
					),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
	}

	/**
	 * Checks if a given request has access to read blocks.
	 *
	 * @since 5.0.0
	 *
	 * @global WP_Post $post Global post object.
	 *
	 * @param WP_REST_Request $request Request.
	 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
	 */
	public function get_item_permissions_check( $request ) {
		global $post;

		$post_id = isset( $request['post_id'] ) ? (int) $request['post_id'] : 0;

		if ( $post_id > 0 ) {
			$post = get_post( $post_id );

			if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) {
				return new WP_Error(
					'block_cannot_read',
					__( 'Sorry, you are not allowed to read blocks of this post.' ),
					array(
						'status' => rest_authorization_required_code(),
					)
				);
			}
		} else {
			if ( ! current_user_can( 'edit_posts' ) ) {
				return new WP_Error(
					'block_cannot_read',
					__( 'Sorry, you are not allowed to read blocks as this user.' ),
					array(
						'status' => rest_authorization_required_code(),
					)
				);
			}
		}

		return true;
	}

	/**
	 * Returns block output from block's registered render_callback.
	 *
	 * @since 5.0.0
	 *
	 * @global WP_Post $post Global post object.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
	 */
	public function get_item( $request ) {
		global $post;

		$post_id = isset( $request['post_id'] ) ? (int) $request['post_id'] : 0;

		if ( $post_id > 0 ) {
			$post = get_post( $post_id );

			// Set up postdata since this will be needed if post_id was set.
			setup_postdata( $post );
		}

		$registry   = WP_Block_Type_Registry::get_instance();
		$registered = $registry->get_registered( $request['name'] );

		if ( null === $registered || ! $registered->is_dynamic() ) {
			return new WP_Error(
				'block_invalid',
				__( 'Invalid block.' ),
				array(
					'status' => 404,
				)
			);
		}

		$attributes = $request->get_param( 'attributes' );

		// Create an array representation simulating the output of parse_blocks.
		$block = array(
			'blockName'    => $request['name'],
			'attrs'        => $attributes,
			'innerHTML'    => '',
			'innerContent' => array(),
		);

		// Render using render_block to ensure all relevant filters are used.
		$data = array(
			'rendered' => render_block( $block ),
		);

		return rest_ensure_response( $data );
	}

	/**
	 * Retrieves block's output schema, conforming to JSON Schema.
	 *
	 * @since 5.0.0
	 *
	 * @return array Item schema data.
	 */
	public function get_item_schema() {
		if ( $this->schema ) {
			return $this->schema;
		}

		$this->schema = array(
			'$schema'    => 'http://json-schema.org/schema#',
			'title'      => 'rendered-block',
			'type'       => 'object',
			'properties' => array(
				'rendered' => array(
					'description' => __( 'The rendered block.' ),
					'type'        => 'string',
					'required'    => true,
					'context'     => array( 'edit' ),
				),
			),
		);

		return $this->schema;
	}
}

Changelog

Version Description
5.0.0 Introduced.