WordPress provides predefined categories for the blocks like “text“, “media“, “design“, “widgets“, and so on. You can easily use them while registering a custom Gutenberg block, and you only need to add the category slug into the block.json file.
Why do we need to register a custom category?
If you have multiple custom blocks for your projects, then it would be amazing to assign all of them to a custom category. This way, you can easily organize all of the custom Gutenberg blocks.
How to register a custom category?
We need to use the “block_categories_all” filter hook for registering a custom category. This filter takes a callback function, and we will attach the new custom category with the existing categories.
💡The “block_categories_all” filter introduced in WordPress 5.8.
You can add the following filter to your theme’s functions.php or create a custom plugin.
add_filter("block_categories_all", "set_block_category_cb");
Prepare set_block_category_cb function
Now, we will write the callback function. The callback function takes the $categories as a parameter and adds the new custom category to it and returns the modified array using the array_merge function.
In the following function, we have added a new category with the title “Petitions Manager Blocks“, and the slug is “bptm-gt-blocks“.
🚨Note that the slug must be unique, and we will use this slug value in the block.json file.
function set_block_category( $categories ) { return array_merge( $categories,[ [ 'title' => 'Petitions Manager Blocks', 'slug' => 'bptm-gt-blocks' ], ] ); }
Output:
Congratulations! Now you have successfully registered the custom category.
How to use the custom category?
Open the block.json file, and find the “category” attribute. Now update the value with the registered slug. For example, our custom category slug is “bptm-gt-blocks” and we have set that value in the category attribute.