Gutenberg, WordPress’s block editor, has revolutionized the way we create content. But did you know you can create your own custom Gutenberg blocks to extend its functionality? In this guide, we’ll walk you through the process of building a custom Gutenberg block from scratch. Whether you’re a beginner or an experienced developer, this tutorial will help you unlock the full potential of WordPress development.
Gutenberg blocks are the building blocks of the WordPress block editor. They allow users to add and arrange content elements like paragraphs, images, buttons, and more. By creating custom blocks, you can tailor the editor to meet specific needs, making it easier for clients or users to manage their content.
Before we dive in, ensure you have the following:
npm init -y
This will create a package.json file for managing dependencies.
<br /><!--?php /* Plugin Name: Custom Gutenberg Block Description: A custom Gutenberg block created from scratch. Version: 1.0 Author: Your Name */ function custom_gutenberg_block_init() { register_block_type(__DIR__ . '/build'); } add_action('init', 'custom_gutenberg_block_init'); ?--><br />
npm install @wordpress/scripts --save-dev
import { registerBlockType } from '@wordpress/blocks'; import { RichText } from '@wordpress/block-editor'; registerBlockType('custom-gutenberg-block/example', { title: 'Custom Block', icon: 'smiley', category: 'common', attributes: { content: { type: 'string', source: 'html', selector: 'p', }, }, edit: (props) => { const { attributes, setAttributes } = props; const { content } = attributes; const onChangeContent = (newContent) => { setAttributes({ content: newContent }); }; return ( <RichText tagName="p" onChange={onChangeContent} value={content} /> ); }, save: (props) => { const { attributes } = props; const { content } = attributes; return <RichText.Content tagName="p" value={content} />; }, });
npx wp-scripts build
To style your block, create a style.css file in the src folder and import it into your index.js file:
import './style.css';
Then, rebuild your block using npx wp-scripts build.