Registering custom block categories

Hey folks,

Maybe this is a more Bud related topic, but I am wondering where I can register custom block categories. I find the way to register/unregister block types via your example.plugin.tsx quite elegant. Is there an easy way to register custom block categories as well?

For example, in my example.block.tsx I have:

/* Block category */
export const category = `custom-category`

And my example.plugin.tsx:

/** Plugin render */
export const render = () => {
  useEffect(() => {
    // Unregister all blocks that aren't in the text or media categories
    getBlockTypes()
      .filter((block) => ![`cwicly`, `custom-category`, `widgets`].includes(block?.category))
      .map((block) => block.name)
      .map(unregisterBlockType);
  }, []);

  return null;
};

WordPress registers block categories with PHP not JS, so it won’t be possible to do this through Bud. You’ll need to use a PHP filter.

https://developer.wordpress.org/reference/hooks/block_categories_all/

1 Like

Hi @thunderdw

Thanks for your prompt reply. With Sage, I could use the filters.php in the app folder. What would be the equivalent in Radicle to register filters? The theme.php?

One way to do it would be to use a service provider to do it and then put the block categories into config. This package does that. It also registers post types/taxonomies, which Radicle already has built in, but you could just skip those fields and use the other features.

2 Likes

Awesome, that was easier than expected! Thanks, @thunderdw :slight_smile:

1 Like

Quick Comment several months later new details
Radicle is now shipping with an example.plugin.tsx
its briefly mentioned in the documentation here

but if you are trying to register new block categories this will filter them out unless you deactivate or probably better choice modify it to include your new categories

/** Plugin render */
export const render = () => {
  useEffect(() => {
    // Unregister all blocks that aren't in the text, media, design, or widget categories
    // Keep the `core/block` block so that the editor doesn't break
    getBlockTypes()
      .filter((block) => ![`text`, `media`, `design`, `widgets`, 'add-new-block-category', ].includes(block?.category))
      .filter((block) => block.name !== `core/block`)
      .map((block) => block.name)
      .map(unregisterBlockType);
  }, []);

I found this out the hard way - hopefully this saves someone some time :slight_smile: