How to list and re-arrange or manipulate Gutenberg Block Categories in Wordpress

Viewed 1765

Anyone know how to re-arrange, manipulate the Block Categories in the Gutenberg Editor in Wordpress I can't even return a list of them as you can with the Blocks themselves, all I can find is 'getCategories' which doesn't seem do anything... the new documentation is not great at all.

3 Answers

This did the trick for me to register a custom Guttenberg block and make it the first option in WP Admin editor:

function custom_block_category( $categories ) {
    $custom_block = array(
        'slug'  => 'my-blocks',
        'title' => __( 'My Test Blocks', 'my-blocks' ),
    );

    $categories_sorted = array();
    $categories_sorted[0] = $custom_block;

    foreach ($categories as $category) {
        $categories_sorted[] = $category;
    }

    return $categories_sorted;
}
add_filter( 'block_categories', 'custom_block_category', 10, 2);

Here's a shorter solution:

function custom_block_category( $categories ) {
    return array_merge(
        array(
            array(
                'slug' => 'my-blocks',
                'title' => __( 'My Test Blocks', 'my-blocks' ),
            ),
        ),
        $categories
    );
}
add_filter( 'block_categories', 'custom_block_category', 10, 2 );

The above solution is Good for PHP. But if someone wants to do that using JavaScript, there is also a good way.

import { getCategories, setCategories } from '@wordpress/blocks';

const customBlockCategory = {
   slug: 'my-custom-block-category',
   title: __('My Custom Block Category', 'text-domain'),
   icon: 'wordpress', // or an SVG icon component as Element
}

// Then Just set you block category.
setCategories([
    ...getCategories(), // This is all default registered categories.
    customBlockCategory,
]);

If you want to add the category at first just append your block first, like this -

setCategories([
    customBlockCategory,
    ...getCategories(),
]);

Hope, this will help many people.

Related