The WordPress block editor allows registering categories for custom blocks. So, if you have many custom blocks you may want to have them be under their own category. Here’s how we do it, and still maintain the backward compatibility for WordPress lower than 5.8.
<?php
function zwp_block_categories($existingCategories)
{
$customCategories = [
[
'slug' => 'my-category-one',
'title' => __('My Category One', 'domain'),
],
[
'slug' => 'my-category-two',
'title' => __('My Category Two', 'domain'),
],
];
return array_merge($customCategories, $existingCategories);
}
global $wp_version;
add_filter(
'block_categories' . (version_compare($wp_version, '5.8', '>=') ? '_all' : ''),
'zwp_block_categories',
99
);
The above code snippet will add 2 new categories. Adjust the code to fit your needs and you’re done. 🙂
Append categories
The return line will currently prepend the categories, so your new custom categories will be on the top of the list. If you want to append them instead, so they appear at the end, replace the return line with this one:
return array_merge($existingCategories, $customCategories);
Nice. Thanks for the example.