How can I create a custom Gutenberg block for my theme?
Asked on Oct 13, 2025
Answer
Creating a custom Gutenberg block involves registering a new block type using JavaScript and PHP. This process allows you to extend the WordPress block editor with your custom functionality.
<!-- BEGIN COPY / PASTE -->
// JavaScript: Registering a custom block
wp.blocks.registerBlockType('mytheme/custom-block', {
title: 'Custom Block',
icon: 'smiley',
category: 'common',
edit: function(props) {
return wp.element.createElement('p', {}, 'Hello, Gutenberg!');
},
save: function(props) {
return wp.element.createElement('p', {}, 'Hello, Gutenberg!');
}
});
// PHP: Enqueue block editor assets
function mytheme_enqueue_block_editor_assets() {
wp_enqueue_script(
'mytheme-blocks',
get_template_directory_uri() . '/blocks/custom-block.js',
array('wp-blocks', 'wp-element')
);
}
add_action('enqueue_block_editor_assets', 'mytheme_enqueue_block_editor_assets');
<!-- END COPY / PASTE -->Additional Comment:
- Ensure you have Node.js and npm installed to build your block's JavaScript files.
- Place the JavaScript code in a file like "custom-block.js" within your theme's directory.
- Use "wp-scripts" to compile your block JavaScript if using ES6 or JSX syntax.
- Register your block in the "init" action hook for proper loading.
Recommended Links: