Introduction
The Gutenberg editor changed the way we build and manage content in WordPress. While core blocks offer basic functionality, custom Gutenberg blocks enable developers to tailor unique editing experiences. In this guide, you’ll learn how to create custom blocks using JavaScript (React) and PHP.
Why Create Custom Blocks?
- Tailored Editing: Provide a better content-editing experience for specific use cases.
- Reusability: Create reusable, modular content elements.
- Branding Control: Enforce design standards across pages.
Tools You’ll Need
- WordPress (local or dev server)
- Node.js and npm installed
- Basic knowledge of JavaScript (ES6) and React
- A code editor like VS Code
Step-by-Step: Create Your First Block
Setup Plugin Directory
Create a plugin folder in wp-content/plugins
, e.g., my-custom-block
.
Create Plugin Header (PHP)
<?php
/**
* Plugin Name: My Custom Block
*/
function my_block_register() {
wp_register_script(
'my-block-script',
plugins_url( 'block.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-editor' )
);
register_block_type( 'myplugin/my-custom-block', array(
'editor_script' => 'my-block-script',
) );
}
add_action( 'init', 'my_block_register' );
?>
Create the JavaScript Block File
Inside the plugin folder, create a block.js
file:
const { registerBlockType } = wp.blocks;
const { RichText } = wp.blockEditor;
registerBlockType('myplugin/my-custom-block', {
title: 'My Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
},
edit({ attributes, setAttributes }) {
return (
<RichText
tagName="p"
value={attributes.content}
onChange={(content) => setAttributes({ content })}
placeholder="Enter custom block content"
/>
);
},
save({ attributes }) {
return <RichText.Content tagName="p" value={attributes.content} />;
},
});
Activate the Plugin
Go to the WordPress Dashboard → Plugins and activate “My Custom Block.”
Optional Enhancements
- Add CSS styles for your block
- Use
@wordpress/scripts
to compile JSX with Babel and Webpack - Create dynamic blocks with PHP render callbacks
Conclusion
Gutenberg opens the door to fully custom editing experiences in WordPress. By creating your own blocks, you take control of how your users and clients interact with content. Start small, follow best practices, and grow your skills block by block.
Have questions about block development? Drop them in the comments or check the official Gutenberg developer docs.