The Gutenberg block editor has revolutionized how content is created in WordPress, offering a more visual and flexible editing experience. Creating a custom Gutenberg block allows you to extend the editor with your own functionalities and design elements. In this tutorial, we’ll guide you through the process of building a custom Gutenberg block from scratch, complete with code examples and best practices.
1. Setting Up Your Development Environment
Before creating a custom block, you need to set up a development environment:
- Install Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from nodejs.org.
- Create a New Plugin: Navigate to
wp-content/plugins
and create a new folder for your plugin, e.g.,custom-gutenberg-block
. - Create the Main Plugin File: Inside your plugin folder, create a PHP file, e.g.,
custom-gutenberg-block.php
, and add the plugin header:
<?php
/**
* Plugin Name: Custom Gutenberg Block
* Description: A plugin to create a custom Gutenberg block.
* Version: 1.0
* Author: Your Name
* License: GPL2
*/
- Enqueue Block Scripts and Styles: Add code to enqueue your block’s JavaScript and CSS files:
function custom_gutenberg_block_assets() {
wp_enqueue_script(
'custom-block-editor-script',
plugins_url('/build/index.js', __FILE__),
array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor'),
filemtime(plugin_dir_path(__FILE__) . 'build/index.js')
);
wp_enqueue_style(
'custom-block-editor-style',
plugins_url('/build/editor.css', __FILE__),
array('wp-edit-blocks'),
filemtime(plugin_dir_path(__FILE__) . 'build/editor.css')
);
wp_enqueue_style(
'custom-block-style',
plugins_url('/build/style.css', __FILE__),
array(),
filemtime(plugin_dir_path(__FILE__) . 'build/style.css')
);
}
add_action('enqueue_block_assets', 'custom_gutenberg_block_assets');
2. Creating the Block JavaScript
- Initialize the Block Project: In your plugin folder, create a new folder named
src
. Inside this folder, create a file namedindex.js
. This file will contain the code for your block. - Add Block Registration Code: In
index.js
, register your custom block:
const { registerBlockType } = wp.blocks;
const { RichText } = wp.blockEditor;
const { Fragment } = wp.element;
registerBlockType('custom/block', {
title: 'Custom Block',
icon: 'smiley',
category: 'layout',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
},
edit: ({ attributes, setAttributes }) => {
const { content } = attributes;
return (
<Fragment>
<RichText
tagName="p"
value={content}
onChange={(newContent) => setAttributes({ content: newContent })}
placeholder="Enter content here..."
/>
</Fragment>
);
},
save: ({ attributes }) => {
const { content } = attributes;
return <RichText.Content tagName="p" value={content} />;
},
});
3. Compiling Your Block Code
To compile your JavaScript code into a format that WordPress can use, follow these steps:
- Install Development Dependencies: Navigate to your plugin folder in the terminal and run:
npm init -y
npm install @wordpress/scripts --save-dev
- Add Build Scripts: In your
package.json
file, add the following scripts:
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start"
}
- Create a Configuration File: Create a
webpack.config.js
file in your plugin folder to specify build configurations:
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
module.exports = {
...defaultConfig,
entry: {
'index': './src/index.js',
},
output: {
path: __dirname + '/build',
filename: '[name].js',
publicPath: '/wp-content/plugins/custom-gutenberg-block/build/',
},
};
- Build Your Block: Run the build command to compile your code:
npm run build
4. Adding Block Styles
To style your block, add CSS files:
- Create CSS Files: In your
src
folder, createeditor.css
andstyle.css
. Add styles specific to the editor and frontend, respectively. - Example CSS:
/* editor.css */
.wp-block-custom-block {
border: 1px solid #ccc;
padding: 16px;
}
/* style.css */
.wp-block-custom-block {
font-size: 18px;
color: #333;
}
- Compile CSS: Make sure CSS files are included in the build process as shown in the
custom_gutenberg_block_assets
function.
5. Testing Your Block
- Activate Your Plugin: Go to the WordPress admin dashboard, navigate to Plugins, and activate your custom Gutenberg block plugin.
- Test in the Block Editor: Create or edit a post or page and add your custom block to verify it works as expected.
6. Extending Functionality
You can enhance your block with additional features:
- Add Block Variations: Create different variations of your block for various use cases.
- Use Advanced Controls: Leverage controls from
@wordpress/components
for more complex configurations. - Integrate with External APIs: Fetch data from external APIs and display it within your block.
7. Publishing Your Block
When your block is ready for release:
- Document Your Block: Provide clear documentation on how to use and configure the block.
- Submit to the Block Directory: Consider submitting your block to the WordPress Block Directory.
Conclusion
Creating a custom Gutenberg block in WordPress allows you to enhance the block editor with your own functionalities and design elements. By following this tutorial, you can build and customize blocks to fit your needs, offering a more flexible and tailored content creation experience. Experiment with additional features and styles to make your blocks even more powerful!