Hey there, WordPress fans! Today we’re diving into the exciting world of Gutenberg blocks. If you’re using WordPress 5.0 or later, you’ve probably interacted with these handy little building blocks. But did you know you can create your own? Yep, you can—and I’ll show you how, step by step. Let’s get started!
First, we need to create a new folder for our block in the wp-content/plugins
directory. Let’s call it my-custom-block
.
Next, in the my-custom-block
directory, create two new files: my-custom-block.php
and block.js
.
Open the my-custom-block.php
file and add the following code to register our new block:
This PHP file is set up as a minimal WordPress plugin that will register and enqueue our JavaScript file block.js
.
Now let’s dive into the fun part: creating the block itself. Open the block.js
file and add the following code:
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;
registerBlockType('my-custom-block/my-block', {
title: 'My Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'string',
source: 'children',
selector: 'p',
}
},
edit: (props) => {
return props.setAttributes({ content }) }
placeholder="Enter some text..."
/>;
},
save: (props) => {
return ;
}
});
In this JavaScript file, we use registerBlockType()
to define a new block. Our block has a title, an icon, a category, attributes (to save its internal state), and edit()
and save()
functions for editing and saving the block content.
To bring our block to life, we need to activate it from the WordPress dashboard. Go to Plugins, find “My Custom Block” in the list, and click ‘Activate’.
Your block will now be available in the block editor! You can add it to a post or a page just like any other block, and it will allow you to enter and save text.
Here’s the complete code for your reference:
my-custom-block.php
block.js
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;
registerBlockType('my-custom-block/my-block', {
title: 'My Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'string',
source: 'children',
selector: 'p',
}
},
edit: (props) => {
return props.setAttributes({ content }) }
placeholder="Enter some text..."
/>;
},
save: (props) => {
return ;
}
});
There you have it: your very own custom WordPress block, built from scratch. With these basics down, the possibilities are endless—so start creating!
Enables the creation of unique, personalized landing pages at scale by offering unlimited placeholders for dynamic content.
Essential for crafting content-rich, unique pages for each visitor or target group, optimizing for local SEO, e-commerce variability, or specific event details.