钩子文档

block_categories_all

💡 云策文档标注

概述

block_categories_all 是一个 WordPress 过滤器,用于修改块类型的默认分类数组。它允许开发者在块编辑器中添加、移除或重新排序块分类,以自定义块的组织方式。

关键要点

  • 过滤器名称:block_categories_all,用于过滤块类型的分类数组。
  • 参数:$block_categories(数组,块分类数组)和 $block_editor_context(WP_Block_Editor_Context 对象,当前块编辑器上下文)。
  • 引入版本:WordPress 5.8.0,取代了旧的 block_categories 过滤器。
  • 用途:常用于添加自定义块分类,例如通过 array_unshift 或 array_merge 操作。
  • 兼容性注意事项:在 WordPress 5.8 及以上版本使用,旧版本需检查 WP_Block_Editor_Context 类的存在以进行特性检测。
  • 错误处理:建议检查分类是否已存在,避免重复添加导致错误。

代码示例

// 添加自定义块分类示例
add_filter( 'block_categories_all', 'wpdocs_add_new_block_category', 10, 2 );
function wpdocs_add_new_block_category( $block_categories, $block_editor_context ) {
    // 检查上下文,确保在块编辑器中使用
    if ( ! ( $block_editor_context instanceof WP_Block_Editor_Context ) ) {
        return $block_categories;
    }
    
    // 添加新分类
    return array_merge(
        $block_categories,
        [
            [
                'slug'  => 'my-block-category',
                'title' => esc_html__( 'My Block Category', 'text-domain' ),
                'icon'  => 'wordpress',
            ],
        ]
    );
}

注意事项

  • 在 WordPress 5.8 中,$block_editor_context 可能是 WP_Block_Editor_Context 对象或字符串,回调函数中应进行类型检查。
  • 旧版 block_categories 过滤器传递 WP_Post 实例作为第二个参数,迁移时需调整代码以处理 WP_Block_Editor_Context。
  • 避免重复声明相同分类,建议在添加前检查分类 slug 是否已存在。

📄 原文内容

Filters the default array of categories for block types.

Parameters

$block_categoriesarray[]
Array of categories for block types.
$block_editor_contextWP_Block_Editor_Context
The current block editor context.

Source

$block_categories = apply_filters( 'block_categories_all', $block_categories, $block_editor_context );

Changelog

Version Description
5.8.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Adding a new (custom) block category and show that category at the top

    // Adding a new (custom) block category and show that category at the top
    add_filter( 'block_categories_all', 'example_block_category', 10, 2);
    function example_block_category( $categories, $post ) {
    	
    	array_unshift( $categories, array(
    		'slug'	=> 'example',
    		'title' => 'Example'
    	) );
    
    	return $categories;
    }

  2. Skip to note 8 content

    Adding a new (custom) block category.

    /**
     * Adding a new (custom) block category.
     *
     * @param   array $block_categories                         Array of categories for block types.
     * @param   WP_Block_Editor_Context $block_editor_context 	The current block editor context.
     */
    function wpdocs_add_new_block_category( $block_categories, $block_editor_context ) {
    	// You can add extra validation such as seeing which post type
    	// is used to only include categories in some post types.
    	// if ( in_array( $block_editor_context->post->post_type, ['post', 'my-post-type'] ) ) { ... }
    
    	return array_merge(
    		$block_categories,
    		[
    			[
    				'slug'  => 'my-block-category',
    				'title' => esc_html__( 'My Block Category', 'text-domain' ),
    				'icon'  => 'wordpress', // Slug of a WordPress Dashicon or custom SVG
    			],
    		]
    	);
    }
    
    add_filter( 'block_categories_all', 'wpdocs_add_new_block_category' );

  3. Skip to note 9 content

    Just a note that in base version WP 5.8, $block_editor_context can be either an object or a string. If you are using this filter and type hinting your callback, this could be the cause of the errors you’re undoubtedly seeing.

    Using @heldervilela code above as an example, you may need to do this:

    /**
     * Adding a new (custom) block category.
     *
     * @param   array $block_categories                                Array of categories for block types.
     * @param   WP_Block_Editor_Context|string $block_editor_context   The current block editor context, or a string defining the context.
     */
    function wpdocs_add_new_block_category( $block_categories, $block_editor_context ) {
        // Check the context of this filter, return default if not in the post/page block editor.
        // Alternatively, use this check to add custom categories to only the customizer or widget screens.
        if ( ! ( $block_editor_context instanceof WP_Block_Editor_Context ) ) {
            return $block_categories;
        }
    
        // You can add extra validation such as seeing which post type
        // is used to only include categories in some post types.
        // if ( in_array( $block_editor_context->post->post_type, ['post', 'my-post-type'] ) ) { ... }
     
        return array_merge(
            $block_categories,
            [
                [
                    'slug'  => 'my-block-category',
                    'title' => esc_html__( 'My Block Category', 'text-domain' ),
                    'icon'  => 'wordpress', // Slug of a WordPress Dashicon or custom SVG
                ],
            ]
        );
    }
     
    add_filter( 'block_categories_all', 'wpdocs_add_new_block_category' );

  4. Skip to note 10 content

    This snippet allows you to add block categories on WP 5.8 and below.

    if ( version_compare( $GLOBALS['wp_version'], '5.8-alpha-1', '<' ) ) {
    	add_filter( 'block_categories', 'wpdocs_add_block_category', 10, 2 );
    } else {
    	add_filter( 'block_categories_all', 'wpdocs_add_block_category', 10, 2 );
    }
    
    /**
     * Adding a new (custom) block category.
     *
     * @param   array                   $block_categories       Array of categories for block types.
     * @param   WP_Block_Editor_Context $block_editor_context   The current block editor context.
     */
    function wpdocs_add_block_category( $block_categories, $block_editor_context ) {
    	return array_merge(
    		$block_categories,
    		array(
    			array(
    				'slug'  => 'block-slug',
    				'title' => __( 'Block Category Title', 'text-domain' ),
    			),
    		)
    	);
    }

  5. Skip to note 11 content

    // Boilerplate - a prefix: change it as per yours
    
      if ( ! function_exists( 'boilerplate_register_block_category' ) ) {
    
    	// wordpress version check and load filter for block category
    
    	if( version_compare( $GLOBALS['wp_version'], '5.7', '<' ) ) {
    		add_filter( 'block_categories', 'boilerplate_register_block_category', 10, 2 );
    	} else {
    		add_filter( 'block_categories_all', 'boilerplate_register_block_category', 10, 2 );
    	}
    
    	/**
    	 * Register custom category for blocks
    	 */
    
    	function boilerplate_register_block_category( $categories, $post ) {
    		return array_merge(
    			array(
    				array(
    					'slug'  => 'boilerplate',
    					'title' => __( 'Boilerplate', 'boilerplate' ),
    				),
    			),
    			$categories,
    		);
    	}
    
      }

  6. Skip to note 12 content

    Declare a block category just once, or it will throw an error. It is useful to know if you split your code in several plugins.

    function my_block_category( $categories, $post ) {
            
        $category = array(
            'slug'  => 'my-category-slug',
            'title' => 'My category name,
        );
    
        if ( is_array( $categories ) ) {
            $existingSlugs = array_column( $categories, 'slug' );
    
            if ( is_array( $existingSlugs ) ) {
                if ( in_array( $category['slug'], $existingSlugs ) ) {
                    return $categories; // Bail early if category exists
                }
            }
        }
            
        array_unshift( $categories, $category ); // Add category on top of pile
    
        return $categories;
    }