Block categories are a great way to organize blocks within the block inserter. There are a number of default categories you can use, but if a category doesn’t fit well with your block, you can make your own!
In order to create a category of your own you will need to hook into the block_categories
filter. In the code snippet below we’re going to check if our category exists before adding it. The filter callback will be given the existing categories as an array and we need to ensure we’re also returning our modified array.
First we will use wp_list_pluck
to create an array of category slugs from the $categories
array passed to our callback. We then use in_array
to check if our slug exists in the $categories
array. If our category slug exists we will return the unmodifed array or we will merge in our category array definition with array_merge
, returning the modified array.
The required properties for a block category is a slug
, and a title
. You can also set an icon
which can be a slug of a WordPress Dashicon. If you want to set a custom SVG icon, you’ll need to set and render it on the front-end. You can see an example from CoBlocks in the image above.
I did find that icons might be removed in a future version of Gutenberg. The idea behind removing icons is that they are a distraction and add cognitive load. You can track the issue on GitHub.
You can read more in the Gutenberg Handbook.