Basically I want to develop a wordpress block theme.For easy to customize I want to add some custom block in my theme.But I don’t want to create a plugin for this.Custom block will be inside my theme.When someone install my theme he will get those custom block built in with my theme.How can I achive it and how can I organize my folder structure as well??
2
Answers
All you need to do is to create a src folder inside your theme then put your block folders there (shown structure below).
Folder Structure may be:
— theme folder
–> src
–> block-folder > block files(edit.js, index.js, save.js etc.)
For block files:
Now it’s time to install
wp-scripts
package to work with wp blocks. For that, Update your package.json file adding below lines. then in terminal go to the theme folder and command ‘npm install‘ it will install all your dependencies packages then give the ‘npm start‘ command.Note: You need to register block via
register_block_type
function for PHP way orregisterBlockType
for JS way. Otherwise, above code won’t work. Above codes will create your files only.I just had to do the same: Register a custom block inside of my theme.
Create block inside of
src/blocks
First, I created the block inside
src/blocks
usingnpx @wordpress/create-block my-block
. The block is now located in{theme}/src/blocks/my-block
.Build the block
Then, I built the block using
npm run build
.Register
block.json
from the build folderLastly, I registered the block using the
block.json
metadata file of the build:functions.php