Introduction
In the previous articles, you learned about Gutenberg and how to set up your development environment for custom block creation. Now, it’s time to take the next step: building your very first custom Gutenberg block.
In this guide, we’ll walk you through creating a simple block, explaining the structure, code, and functionality you’ll need to get started. By the end of this article, you’ll have a solid understanding of how to build blocks that can be used within the WordPress Block Editor.
What is a Gutenberg Block?
A Gutenberg block is a self-contained unit of content that can be added, moved, and edited within the WordPress Block Editor. Blocks allow users to create complex layouts with ease, and custom blocks extend the default WordPress functionality by enabling you to create blocks tailored to your specific needs.
Step 1: Set Up the Block Folder Structure
First, let’s set up the folder and file structure for your custom Gutenberg block inside your theme or plugin.
- Navigate to Your Theme: Open your terminal or command prompt and navigate to the theme directory you set up in the previous article:
cd wp-content/themes/your-theme-child
- Create a Block Folder: Inside your theme directory, create a folder called
blocks
to store your custom block files.
mkdir blocks
- Create a Block Subfolder: Inside the
blocks
folder, create a new folder for your first block. Let’s name itmy-first-block
.
mkdir blocks/my-first-block
- Create Block Files: In the
my-first-block
folder, create the following files:
block.json
(this will define your block’s metadata)index.js
(the main JavaScript file for your block)style.css
(for block-specific styling)
Your folder structure should now look like this:
wp-content/
themes/
your-theme-child/
blocks/
my-first-block/
block.json
index.js
style.css
Step 2: Define Block Metadata in block.json
The block.json
file defines the metadata for your block, including its name, title, category, and icon.
Open block.json
and add the following content:
{
"apiVersion": 2,
"name": "your-theme/my-first-block",
"title": "My First Block",
"category": "common",
"icon": "smiley",
"description": "A custom Gutenberg block created for learning purposes.",
"supports": {
"html": false
},
"attributes": {
"content": {
"type": "string",
"source": "html",
"selector": "p"
}
},
"textdomain": "your-theme",
"editorScript": "file:./index.js",
"style": "file:./style.css"
}
Explanation:
apiVersion
: The version of the Block API you’re using. We are using version 2, which is the most recent.name
: The block’s unique identifier. It follows the formatnamespace/block-name
. Replaceyour-theme
with your theme or plugin name.title
: The name displayed in the WordPress Block Editor.category
: The block category under which the block will appear in the editor. Use “common” for general-purpose blocks.icon
: The block icon. You can choose from Dashicons.supports
: Set tofalse
for HTML if you don’t want to allow custom HTML within the block.attributes
: Define the block attributes. Here, we define a simple string attributecontent
that will store the block’s content.editorScript
: The JavaScript file to load for the block editor.style
: The CSS file that contains the block’s styles.
Step 3: Write the Block Code in index.js
Now let’s add the JavaScript code that will define the block’s behavior in the editor.
Open index.js
and add the following code:
import { registerBlockType } from '@wordpress/blocks';
import { RichText } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
registerBlockType('your-theme/my-first-block', {
title: __('My First Block', 'your-theme'),
description: __('A simple Gutenberg block for learning purposes.', 'your-theme'),
category: 'common',
icon: 'smiley',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
},
edit: (props) => {
const {
attributes: { content },
setAttributes,
} = props;
const onChangeContent = (newContent) => {
setAttributes({ content: newContent });
};
return (
<RichText
tagName="p"
value={content}
onChange={onChangeContent}
placeholder={__('Enter your text here...', 'your-theme')}
/>
);
},
save: (props) => {
const {
attributes: { content },
} = props;
return <RichText.Content tagName="p" value={content} />;
},
});
Explanation:
registerBlockType
: Registers your custom block with WordPress. It takes two arguments: the block’s unique name and an object defining its properties.edit
function: Defines how the block appears in the editor. In this case, we use theRichText
component to allow users to enter and edit text in the block.save
function: Determines how the block’s content is saved. Here, theRichText.Content
component ensures the entered content is saved as a paragraph.
Step 4: Add Styling in style.css
Now let’s add some basic styling to the block. Open the style.css
file and add the following CSS:
.wp-block-your-theme-my-first-block {
background-color: #f5f5f5;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
}
Explanation:
.wp-block-your-theme-my-first-block
: This class is automatically generated based on the block name. The styles ensure the block has a gray background with padding and a border.
Step 5: Enqueue Scripts and Styles
Finally, we need to enqueue the block’s JavaScript and CSS files in WordPress.
- Open your theme’s
functions.php
file and add the following code:
function my_theme_enqueue_block_assets() {
wp_enqueue_script(
'my-first-block-editor',
get_template_directory_uri() . '/blocks/my-first-block/index.js',
array('wp-blocks', 'wp-element', 'wp-editor'),
filemtime(get_template_directory() . '/blocks/my-first-block/index.js')
);
wp_enqueue_style(
'my-first-block-style',
get_template_directory_uri() . '/blocks/my-first-block/style.css',
array(),
filemtime(get_template_directory() . '/blocks/my-first-block/style.css')
);
}
add_action('enqueue_block_assets', 'my_theme_enqueue_block_assets');
This code ensures that your block’s scripts and styles are loaded when the block editor is used.
Step 6: Test Your Block in WordPress
- Go to your WordPress dashboard.
- Create a new post or page.
- Open the Block Editor, click the “+” button, and search for “My First Block.”
- Add the block to your post or page and test its functionality.
You should now see your custom Gutenberg block, complete with text input and the styles you added. Congratulations, you’ve successfully created your first custom Gutenberg block!
Conclusion
You’ve just built your first custom Gutenberg block from scratch! By understanding the basic structure, attributes, and the registration process, you now have the foundational skills to build more complex blocks in the future. In Day 4, we’ll dive deeper into block attributes and explore how to add more customization options to your blocks.
Stay tuned for more Gutenberg development tips as you continue your journey!
Leave a Reply