How can I create a custom Gutenberg block for my theme?
Asked on Oct 22, 2025
Answer
Creating a custom Gutenberg block involves using JavaScript and WordPress's block editor API to define the block's functionality and appearance. This process typically requires setting up a development environment with Node.js and npm.
<!-- BEGIN COPY / PASTE -->
// Step 1: Set up your environment
// Run these commands in your theme's directory
npm init -y
npm install @wordpress/scripts --save-dev
// Step 2: Create a block
// Create a new file in your theme, e.g., my-block.js
import { registerBlockType } from '@wordpress/blocks';
import { RichText } from '@wordpress/block-editor';
registerBlockType('mytheme/my-block', {
title: 'My Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
},
edit: ({ attributes, setAttributes }) => {
const onChangeContent = (content) => {
setAttributes({ content });
};
return (
<RichText
tagName="p"
onChange={onChangeContent}
value={attributes.content}
/>
);
},
save: ({ attributes }) => {
return <RichText.Content tagName="p" value={attributes.content} />;
},
});
// Step 3: Build the block
// Add a script in package.json to build your block
// "scripts": {
// "build": "wp-scripts build my-block.js"
// }
// Run npm run build to compile your block
<!-- END COPY / PASTE -->Additional Comment:
- Ensure you have Node.js and npm installed on your system to manage dependencies and build processes.
- Use the WordPress block editor's documentation to explore additional block features and customization options.
- Register your block's script and style in WordPress using the "enqueue_block_editor_assets" action hook.
- Consider using the WordPress Block Editor Handbook for more detailed guidance on block development.
Recommended Links: