How to Create a Custom Gutenberg Block Without a Plugin in 5 Easy Steps – 2023

Today we’re getting hands-on with Gutenberg and creating our very own custom block, all without using any plugins. Yep, you heard right. Get your code editor ready!

Step 1: Setup your Development Environment

Before you start, make sure you have Node.js and npm installed on your system. If not, head over to the Node.js website and download it. Once installed, you can check the installed version of Node.js and npm using the following commands:

 
				
					node -v
npm -v

				
			

Step 2: Create a New Block

WordPress provides a package called @wordpress/create-block to simplify the process of creating a new block. Create a new directory for your block, navigate to it, and then run the following command:

				
					npx @wordpress/create-block my-custom-block

				
			

This will create a new block named “my custom block”. Feel free to replace “my-custom-block” with the name of your choice.

Step 3: Build the Block

Inside the “my-custom-block” folder, you’ll find several files and folders that create-block has scaffolded for you. The primary file we’re concerned with is src/edit.js. This file controls how your block will look in the Gutenberg editor.

Open src/edit.js in your code editor and modify the code as follows:

 
				
					import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';

export default function Edit() {
	return (
		<p { ...useBlockProps() }>
			{ __( 'Hello, Gutenberg!', 'my-custom-block' ) }
		</p>
	);
}

				
			

This command will create a build folder containing index.js which is the final built file for your block.

To enqueue this file in WordPress, create a new PHP file in your theme (or child theme) directory, for instance my-custom-block.php, and add the following code:

				
					<?php
function enqueue_my_custom_block() {
    wp_enqueue_script(
        'my-custom-block',
        get_template_directory_uri() . '/my-custom-block/build/index.js',
        array( 'wp-blocks', 'wp-element', 'wp-editor' ),
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'enqueue_my_custom_block' );

				
			

Be sure to replace 'my-custom-block' and '/my-custom-block/build/index.js' with the name of your block and the path to your index.js file, respectively.

Step 5: Activate the Block

The last step is to include this PHP file in your functions.php file. Add the following line to functions.php:

				
					include 'my-custom-block.php';

				
			

Replace 'my-custom-block.php' with the path to your PHP file if necessary.

And there you go! You’ve just created a custom Gutenberg block without a plugin. Open your WordPress editor, add a new block, and you should see your block listed under the category “widgets”.

Table of Contents

Pro Feature

When to Use This Feature

Use Examples