Tutorials on creating custom blocks usually use creating a single block as an example. This makes sense because you may need to create only one custom block, and having a plugin with a single custom block is the best way if you want to share it.
There are many reasons to have several custom blocks in a single plugin, like making a shareable collection of blocks for a type of site or having all the custom blocks for a client’s site in a single plugin.
You can do this in many ways, but most of them include changing the initial folder structure of the plugin created with @wordpress/create-block
and adding custom start and build scripts.
This is the easy way.
You have a main PHP file like name-of-your-plugin.php
and a src
folder with your block that gets built in a build
folder — src/index.js
will create build/index.js
— and this build folder will be what gets used on the site using register_block_type( __DIR__ . '/build' )
.
To create, let’s say, block-a and block-b, you have to move all the contents inside src
to a new folder within, like src/block-a
— instead of src/index.js
you will have src/block-a/index.js
, which will create build/block-a/index.js
.
Then you just have to duplicate the block-a
folder for each new block, like block-b
.
And finally, in the plugin main PHP file use register_block_type( __DIR__ . '/build/block-a' )
and add a new call to the function for each block, for example, register_block_type( __DIR__ . '/build/block-b' )
.
That’s it. Your plugin files and folders will look like this:
/name-of-your-plugin
- /build
- - /block-a
- - - …
- - /block-b
- - - …
- /node_modules
- /src
- - /block-a
- - - …
- - /block-b
- - - …
- .editorconfig
- .gitignore
- name-of-your-plugin.php
- package.json
- package-lock.json
- readme.txt
Inside name-of-your-plugin.php
you will have:
function name_of_your_plugin_block_init() {
register_block_type( __DIR__ . '/build/block-a' );
register_block_type( __DIR__ . '/build/block-b' );
}
add_action('init', 'name_of_your_plugin_block_init');
As you are using the same default folder structure, when you use npm start it will automatically replicate the new folders inside src
to build
.