How to Create a Custom Gutenberg Block in WordPress in 2024: A Step-by-Step Tutorial

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:

  1. 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.
  2. Create a New Plugin: Navigate to wp-content/plugins and create a new folder for your plugin, e.g., custom-gutenberg-block.
  3. 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
*/
  1. 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

  1. Initialize the Block Project: In your plugin folder, create a new folder named src. Inside this folder, create a file named index.js. This file will contain the code for your block.
  2. 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:

  1. Install Development Dependencies: Navigate to your plugin folder in the terminal and run:
npm init -y
npm install @wordpress/scripts --save-dev
  1. Add Build Scripts: In your package.json file, add the following scripts:
"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start"
}
  1. 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/',
},
};
  1. 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:

  1. Create CSS Files: In your src folder, create editor.css and style.css. Add styles specific to the editor and frontend, respectively.
  2. 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;
}
  1. 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

  1. Activate Your Plugin: Go to the WordPress admin dashboard, navigate to Plugins, and activate your custom Gutenberg block plugin.
  2. 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!

Leave a Reply

Your email address will not be published. Required fields are makes.