Block registration lets you add new blocks to the WordPress editor. This helps you create custom content pieces easily.
Block registration in Wordpress
registerBlockType('namespace/block-name', { title: 'Block Title', icon: 'smiley', category: 'common', edit: () => { return <p>Hello from the block editor!</p>; }, save: () => { return <p>Hello from the saved content!</p>; }, });
The first argument is a unique name with a namespace and block name separated by a slash.
The edit function defines what appears in the editor, and save defines what is saved in the post content.
registerBlockType('myplugin/alert', { title: 'Alert Box', icon: 'warning', category: 'widgets', edit: () => <div style={{backgroundColor: 'yellow', padding: '10px'}}>Alert in editor</div>, save: () => <div style={{backgroundColor: 'yellow', padding: '10px'}}>Alert on page</div>, });
registerBlockType('myplugin/simple-text', { title: 'Simple Text', icon: 'text', category: 'text', edit: () => <p>Type your text here</p>, save: () => <p>Type your text here</p>, });
This block shows a button in the editor that counts clicks. The saved content is a simple button text because saved content can't have dynamic state.
import { registerBlockType } from '@wordpress/blocks'; import { useState } from '@wordpress/element'; registerBlockType('myplugin/click-counter', { title: 'Click Counter', icon: 'smiley', category: 'widgets', edit: () => { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)} aria-label="Click counter button"> Clicked {count} times </button> ); }, save: () => { return <button>Click counter saved block</button>; }, });
Blocks must have a unique name with a namespace to avoid conflicts.
The edit function can use React hooks like useState for interactivity in the editor.
The save function returns static content that is saved in the post and shown on the site.
Block registration adds custom blocks to the WordPress editor.
Use registerBlockType with a unique name and provide edit and save functions.
Blocks help create rich, reusable content easily for editors and visitors.