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 } );
} )();