How to Create a Gutenberg Block for Your WordPress Site

How to Create a Gutenberg Block for Your WordPress Site

Creating custom Gutenberg blocks allows you to enhance the content creation experience on your WordPress site by adding customized elements to your posts and pages. Here’s a step-by-step guide to creating a basic Gutenberg block.

Step 1: Set Up Your Development Environment

Before you start, you’ll need the following:

Step 2: Create a Plugin for Your Block

Gutenberg blocks are added to WordPress through plugins. Create a new folder in your /wp-content/plugins directory. You can name it my-custom-block.

Inside that folder, create a PHP file with the same name as your folder:

 * Plugin Name: My Custom Block
 * Description: Adds a custom Gutenberg block to WordPress.
 * Author: Your Name
 * Version: 1.0.0

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.

Step 3: Initialize Your Block’s JavaScript

Create a block.js file inside your plugin’s folder. This JavaScript file will handle the registration and logic of your block.

Use the wp-scripts package to simplify the setup:

npm init
npm install @wordpress/scripts --save-dev

In your package.json, set up a script to build your block:

"scripts": {
    "build": "wp-scripts build"

Step 4: Register Your Block’s JavaScript

Enqueue the JavaScript file in your plugin PHP file using the enqueue_block_editor_assets hook:

function my_custom_block_editor_assets() {
        plugins_url( 'block.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-editor' ),
        filemtime( plugin_dir_path( __FILE__ ) . 'block.js' )
add_action( 'enqueue_block_editor_assets', 'my_custom_block_editor_assets' );

Step 5: Write Your Block’s Code

In your block.js file, use the registerBlockType function from wp.blocks to define your block:

const { registerBlockType } = wp.blocks;

registerBlockType('my-custom-block/hello-world', {
    title: 'Hello World',
    icon: 'universal-access-alt',
    category: 'layout',
    edit: function() {
        return <div>Hello, World!</div>;
    save: function() {
        return <div>Hello, World!</div>;

Step 6: Build and Activate Your Block

Run the build command to compile your JavaScript:

npm run build

Then, activate your plugin through the WordPress dashboard.

Step 7: Use Your Custom Block

With the plugin active, go to a post or page, and add your new “Hello World” block through the Gutenberg editor.

Creating a Gutenberg block involves initializing a block with JavaScript and registering it through PHP in a plugin. From here, you can start experimenting with different attributes, settings, and more advanced functionality within your custom block.

Remember, creating Gutenberg blocks requires an understanding of JavaScript and React, as well as familiarity with the WordPress APIs and hooks. If you’re new to these topics, consider exploring additional resources or tutorials for a deeper dive into block development.

Similar Posts