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

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

  • Anthony 2 months ago

    Nice. Thanks for the example.

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