skip to Main Content

I am trying to add a new category for some custom blocks using the block_categories_all filter.

I am using TwentyTwentyOne theme and putting the code below into the functions.php file. No plugins at all are installed.

When I dump $new_cats the array_merge has been successful but throws header already sent warning.

function wpdocs_add_new_block_category( $block_categories ) {
 
    $new_cats = 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
            ],
        ]
    );
    
    # var_dump($new_cats);

    return ($new_cats);
}
 
add_filter( 'block_categories_all', 'wpdocs_add_new_block_category', 10, 2 );

There must be something simple I am missing here??

2

Answers


  1. Maybe you need add to check context, for example:

    /**
     * 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' );
    

    More information is here

    Login or Signup to reply.
  2. There is nothing wrong in your add_filter( 'block_categories_all', 'wpdocs_add_new_block_category', 10, 2 ); call.

    Block categories are not shown if the category has no blocks in it. Add a new block on that category and you will see your block category.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search