As we know by the provided API from Gutenberg we can create a custom block as
const { registerBlockType } = wp.blocks;
registerBlockType( 'my-namespace/my-block', {
})
but how do I create a wrapper(category like layout) around my custom blocks in gutenberg editor? Let's say I want to have a collector for my custom elements as slider, gallery ...
As we know by the provided API from Gutenberg we can create a custom block as
const { registerBlockType } = wp.blocks;
registerBlockType( 'my-namespace/my-block', {
})
but how do I create a wrapper(category like layout) around my custom blocks in gutenberg editor? Let's say I want to have a collector for my custom elements as slider, gallery ...
Share Improve this question asked Sep 29, 2018 at 15:23 fefefefe 8943 gold badges14 silver badges34 bronze badges2 Answers
Reset to default 16Digging myself deeper in documentation, I got the following result.
There is a way to group your custom blocks around a given category in Gutenberg, and therefore we have the method block_categories_all
. So with a filter, you can extend the default categories with custom ones.
Here is my example:
add_filter( 'block_categories_all', function( $categories, $post ) {
return array_merge(
$categories,
array(
array(
'slug' => 'my-slug',
'title' => 'my-title',
),
)
);
}, 10, 2 );
You can find more on this in the provided API.
It is possible to filter the list of default block categories using the block_categories
filter. Place the code in functions.php
or your-plugin.php
file. Explained here in WordPress Gutenberg Handbook
function my_plugin_block_categories( $categories, $post ) {
if ( $post->post_type !== 'post' ) {
return $categories;
}
return array_merge(
$categories,
array(
array(
'slug' => 'my-category',
'title' => __( 'My category', 'my-plugin' ),
'icon' => 'wordpress',
),
)
);
}
add_filter( 'block_categories', 'my_plugin_block_categories', 10, 2 );
To use an svg icon you can replace the icon in js. Define your icon.
const icon = <svg className='components-panel__icon' width='20' height='20' viewBox='0 0 20 20' aria-hidden='true' role='img' focusable='false' xmlns='http://www.w3.org/2000/svg'>
<rect fill="#ffffff" x="0" y="0" width="20" height="20"/>
<rect fill="#1163EB" x="2" y="2" width="16" height="16" rx="16"/>
</svg>;
and replace the icon using updateCategory
function from wp.blocks;
adding class components-panel__icon
will add a 6px
space to the left side of icon.
( function() {
wp.blocks.updateCategory( 'my-category', { icon: icon } );
} )();