Creating Multiple WordPress Blocks in One Plugin

Creating multiple WordPress blocks within a single plugin simplifies management and enhances functionality. In this guide, you’ll learn how to efficiently create and organize multiple custom blocks in one plugin, making your development process more streamlined and effective.

Step 1: Install the Create Block Tool

In the root of your plugins folder, run the following codes to install the Create Block, which is the official WordPress tool for registering a block.

npx @wordpress/create-block@latest multiple-blocks --namespace multiple-blocks

Step 2: Open the Plugin Folder in Your Code Editor

Once the installation is completed, open the new folder using your preferred code editor (e.g. VS Code). You will see a folder structure similar to the one below:

multiple-blocks/
├── build
├── node_modules
├── src/
│   ├── block.json
│   ├── edit.js
│   ├── editor.scss
│   ├── index.js
│   ├── render.php
│   ├── style.scss
│   ├── view.js
├── .editorconfig
├── .gitignore
├── multiple-blocks.php
├── package-lock.json
├── package.json
├── readme.txt

Step 3: Activate the plugin

Now activate the new plugin inside the Plugins page.

Step 4: Create the second block

Back to the src folder, create a new folder named: first-block and move the rest of the files originally inside the src folder to the new folder. Now make a duplicate of the folder first-block and rename it as second-block:

multiple-blocks/
├── build
├── node_modules
├── src/
│   ├── first-block
│   ├── second-block
├── .editorconfig
├── .gitignore
├── multiple-blocks.php
├── package-lock.json
├── package.json
├── readme.txt

Also, makes some changes to the text areas inside files like edit.js and render.php. Modify the “name” and “title” fields inside block.json so that we know it is from the second-block:

{
	"$schema": "https://schemas.wp.org/trunk/block.json",
	"apiVersion": 3,
	"name": "multiple-blocks/second-block",
	"version": "0.1.0",
	"title": "The Second Block",
	"category": "widgets",
	"icon": "smiley",
	"description": "Example block scaffolded with Create Block tool.",
	"example": {},
	"supports": {
		"html": false
	},
	"textdomain": "multiple-blocks",
	"editorScript": "file:./index.js",
	"editorStyle": "file:./index.css",
	"style": "file:./style-index.css",
	"render": "file:./render.php",
	"viewScript": "file:./view.js"
}

Step 5: Register the second block

In order to show the second-block in the editor screen, we need to register it inside the multiple-blocks.php:

function multiple_blocks_multiple_blocks_block_init() {
	register_block_type(__DIR__ . '/build/first-block');
	register_block_type(__DIR__ . '/build/second-block');
}
add_action('init', 'multiple_blocks_multiple_blocks_block_init');

Don’t forget to run npm run start in the terminal to create a new build folder!

Now you can see both the first-block and second-block as options in the editor screen.