How to register block editor categories

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);
Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

    Your email address will not be published. Required fields are marked *