Creating a block for Gutenberg is easier than it looks. You can learn how to create a block using modern JavaScript ( ESNext and JSX ) from the below resources –
This is the most common and latest approach to creating a custom Gutenberg block. It requires a build process. You can use a command to scaffold a plugin with a boilerplate for the custom block. Reference create-block package.
npx @wordpress/create-block@latest todo-list
But we will create it manually for now to learn more about it. Follow the steps below to create your first simple block.
npm init
. This will create a package.json
file.npm install @wordpress/scripts --save-dev
package.json
file."start": "wp-scripts start",
"build": "wp-scripts build"
src
directory, and inside that, create a directory with your block’s name (e.g., first-block
).{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"title": "First Block",
"name": "learning/first-block",
"version": "0.1.0",
"category": "text",
"icon": "universal-access-alt",
"textdomain": "first-block",
"editorScript": "file:./index.js"
}
index.js
file for the block. This block will not do anything fancy; it will just display text in the editor and the same text on the frontend. For now, the user will not be able to edit the text. We will add that functionality in later sections.edit
and save
functions in the same file, but you can also create them as components in separate files like edit.js
and save.js
, and then import those components into the index.js
file.import { registerBlockType } from "@wordpress/blocks";
import metadata from "./block.json";
// Register the block
registerBlockType(metadata.name, {
edit: function () {
return <p> Hello world! This is my first block. (editor)</p>;
},
save: function () {
return <p> Hello World! This is my first block. (frontend) </p>;
},
});
function register_blocks() {
register_block_type( __DIR__ . '/build/first-block' );
}
add_action( 'init', 'register_blocks' );
Run the build script npm run build
and you will be able to access your first block in the editor.