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??
My Answer:
> To avoid the "header already sent" warning, you should make sure that there is no whitespace or any other output before the `
Here is the corrected code for adding a new block category:
php
function wpdocs_add_new_block_category( $block_categories ) {
$new_cats = array_merge(
$block_categories,
[
[
'slug' => 'custom-blocks',
'title' => 'Custom Blocks',
],
]
);
return $new_cats;
}
add_filter( 'block_categories_all', 'wpdocs_add_new_block_category' );
Make sure to place this code at the end of your functions.php file, after any closing PHP tags `?>` to avoid any whitespace issues. This should add a new category called "Custom Blocks" to the block editor in WordPress.
Rate this post
3 of 5 based on 2157 votesComments