函数文档

register_block_type()

💡 云策文档标注

概述

register_block_type() 是 WordPress 中用于注册块类型的核心函数。推荐使用 block.json 文件中的元数据来注册块类型,以提高可维护性和兼容性。

关键要点

  • 函数接受两个参数:$block_type(可以是块类型名称、block.json 文件路径、包含 block.json 的文件夹路径或 WP_Block_Type 实例)和可选的 $args 数组(对应 WP_Block_Type 的公共属性)。
  • 如果 $block_type 是字符串且指向一个文件,函数会调用 register_block_type_from_metadata() 来处理元数据注册。
  • 返回值为 WP_Block_Type 实例(成功时)或 false(失败时)。
  • 从 WordPress 5.8.0 开始,第一个参数支持 block.json 文件路径。

代码示例

// 使用 block.json 文件路径注册块类型
register_block_type( __DIR__ . '/build/block-a' );

// 使用块类型名称和参数注册
register_block_type( 'my_namespace/my_block', [
    'render_callback' => 'render_callback',
    'attributes'      => [
        'some_string' => [
            'default' => 'default string',
            'type'    => 'string'
        ]
    ]
] );

注意事项

  • 当 $block_type 是 WP_Block_Type 实例时,$args 参数会被忽略。
  • 如果使用文件路径,文件名必须是 "block.json",否则 WordPress 可能无法正确识别。
  • 在设置 dashicon 时,需省略 'dashicons-' 前缀(例如使用 'admin-home')。
  • 对于数组类型的属性,必须指定 'items' 的类型,以避免触发通知。

📄 原文内容

Registers a block type. The recommended way is to register a block type using the metadata stored in the block.json file.

Parameters

$block_typestring|WP_Block_Typerequired
Block type name including namespace, or alternatively a path to the JSON file with metadata definition for the block, or a path to the folder where the block.json file is located, or a complete WP_Block_Type instance.
In case a WP_Block_Type is provided, the $args parameter will be ignored.
$argsarrayoptional
Array of block type arguments. Accepts any public property of WP_Block_Type. See WP_Block_Type::__construct() for information on accepted arguments.

Default:array()

Return

WP_Block_Type|false The registered block type on success, or false on failure.

Source

function register_block_type( $block_type, $args = array() ) {
	if ( is_string( $block_type ) && file_exists( $block_type ) ) {
		return register_block_type_from_metadata( $block_type, $args );
	}

	return WP_Block_Type_Registry::get_instance()->register( $block_type, $args );
}

Changelog

Version Description
5.8.0 First parameter now accepts a path to the block.json file.
5.0.0 Introduced.

User Contributed Notes

  1. Skip to note 10 content

    How to write a plugin with multiple blocks:

    Setting up the src folder

    1. Take the content of the src directory created by @wordpress/create-block and place it in a sub-directory, for example block-a.
    2. Duplicate the sub-directory to make a second block and name it, for example block-b.

    Update the block.json files in each sub-directory to match the blocks’ requirements.

    Registering the Blocks

    After running npm run build corresponding directories will be created in the build directory.

    The two blocks can be registered by pointing to the matching directory in the build folder.

    function wpdocs_create_blocks_mysite_block_init() {
    	
    	register_block_type( __DIR__ . '/build/block-a' );
    	register_block_type( __DIR__ . '/build/block-b' );
    
    }
    add_action( 'init', 'wpdocs_create_blocks_mysite_block_init' );

  2. Skip to note 11 content


    Anonymous User



    You can pass custom $attributes which can be used both on editor and front-end in render_callback :

    register_block_type( 'my_namespace/my_block', [
    	'render_callback' => 'render_callback',
    	'attributes'      => [
    		'some_string' => [
    			'default' => 'default string',
    			'type'    => 'string'
    		],
    		'some_array'  => [
    			'type'  => 'array',
    			'items' => [
    				'type' => 'string',
    			],
    		]
    	]
    ] );

    Important (tested in 5.0.3) : in case of array attributes you MUST specify items type. Otherwise it would trigger a notice.

  3. Skip to note 12 content

    The name of the JSON file, if provided in the $block_type argument, must be “block.json”. If the file does not end with such file name, WordPress will assume it is a path to that file. It seems to be up to the developer choose the file name, but it’s not.

  4. Skip to note 14 content

    Here is an example snippet that I use for one of my own projects

    function mcqa_register_block_related_quiz() {
        if ( ! function_exists( 'register_block_type' ) ) {
            // Block editor is not available.
            return;
        }
    
        register_block_type( 'mcqac/related-quiz', array(
            'editor_script' => 'mcqac-related-quiz-block-script',
            'editor_style'  => 'mcqac-related-quiz-block-editor-style',
            'style'         => 'mcqac-related-quiz-block-frontend-style',
        ) );
    }
    
    // Hook: Editor assets.
    add_action( 'init', 'mcqa_register_block_related_quiz' );

  5. Skip to note 15 content

    If you wish to set a dashicon in the args, you must omit the dashicons- prefix:

    register_block_type(
    	__DIR__ . '/build',
    	array(
    		'icon' => 'admin-home', /* omit 'dashicons-' prefix */
    	)
    );

    This is in contradiction to add_menu_page() which requires the inclusion of the prefix. These should be brought into alignment for consistency in my opinion.

  6. Skip to note 16 content

    To follow on from Michael Levy’s post about registering multiple blocks from the same plugin, I wrote this to automatically register any blocks generated by the npm run build command.

    function wpdocs_register_multiple_blocks() {
    	$build_dir = __DIR__ . '/build';
    
    	foreach ( scandir( $build_dir ) as $result ) {
    		$block_location = $build_dir . '/' . $result;
    
    		if ( ! is_dir( $block_location ) || '.' === $result || '..' === $result ) {
    			continue;
    		}
    
    		register_block_type( $block_location );
    	}
    }
    
    add_action( 'init', 'wpdocs_register_multiple_blocks' );

  7. Skip to note 18 content

    The arguments to register_block_type() function match the instance vars of WP_Block_Type class, i.e., attributes, render_callback, editor_script, editor_style, script and style.

            register_block_type(
                'my-custom-blocks/calendar',
                array(
                    'attributes' => array(
                        'align' => array(
                            'type' => 'string',
                            'enum' => array( 'left', 'center', 'right', 'wide', 'full' ),
                        ),
                        'day' => array(
                            'type' => 'integer',
                        ),
                        'month' => array(
                            'type' => 'integer',
                        ),
                        'year' => array(
                            'type' => 'integer',
                        ),
                    ),
                    'render_callback' => 'render_block_my_custom_blocks_calendar',
                    'editor_script'   => 'calendar-editor-js',
                    'editor_style'    => 'calendar-editor-css',
                    'script'          => 'calendar-frontend-js',
                    'style'           => 'calendar-frontend-css',
    
                )
            );

    This is because the register_block_type() function utilizes the name and arguments provided in the function call to create a new instance of WP_Block_Type class and the instance thus created is registered with the global WP_Block_Type_Registry instance.