🧱 Module 10: Creating Gutenberg Blocks for Your Plugin
Gutenberg (the Block Editor) allows you to add **custom content blocks** visually in WordPress posts and pages. In this module, we’ll build a **“Hello Block”** that you can insert directly into the editor — all powered by your plugin.
Step 1 – Folder Setup
Create a new folder inside your plugin:
my-block-plugin/
│
├── my-block-plugin.php
└── block/
├── index.js
├── editor.css
└── style.css
These files handle the PHP registration, block editor JavaScript, and styles.
Step 2 – Register the Block Script in PHP
'mgb-block-js',
'style' => 'mgb-block-style',
));
}
add_action('init', 'mgb_register_block');
?>
📘 This registers your JS and declares the block type mgb/hello-block.
Step 3 – Create the Block JavaScript (index.js)
const { registerBlockType } = wp.blocks;
const { RichText } = wp.blockEditor;
registerBlockType('mgb/hello-block', {
title: 'Hello Block',
icon: 'smiley',
category: 'widgets',
attributes: {
content: { type: 'string', source: 'html', selector: 'p' }
},
edit: (props) => {
const { attributes: { content }, setAttributes } = props;
return (
wp.element.createElement(
'div',
{ className: 'mgb-hello-block' },
wp.element.createElement(RichText, {
tagName: 'p',
onChange: (value) => setAttributes({ content: value }),
value: content,
placeholder: 'Say hello... 👋'
})
)
);
},
save: (props) => {
return wp.element.createElement(RichText.Content, {
tagName: 'p',
value: props.attributes.content
});
}
});
📘 You now have a block that lets users type text and see it saved to the post!
Step 4 – Add Simple Styles
editor.css (for the block editor):
.mgb-hello-block {
background: #002b36;
border-radius: 10px;
padding: 10px;
color: #00ffa3;
}
style.css (front-end):
.mgb-hello-block p {
font-size: 18px;
color: #00d4ff;
}
Step 5 – Test the Block
- Go to Plugins → Activate “My Gutenberg Block”.
- Open the block editor for any post/page.
- Click ➕ → Search “Hello Block”.
- Type your text → Update the page → View it live.
✅ You’ve built a working custom Gutenberg block!
Bonus – Register Multiple Blocks
You can register more by repeating registerBlockType() in index.js with different names.
No comments:
Post a Comment