You are currently viewing Building a Custom Gutenberg Block for WordPress

Building a Custom Gutenberg Block for WordPress

Spread the love

The WordPress Gutenberg editor has transformed content creation, moving from a classic WYSIWYG interface to a powerful, block-based system. While WordPress offers a robust set of core blocks, the real power for developers lies in extending its capabilities by creating custom blocks. This article will guide you through the foundational steps of building your very own custom Gutenberg block, empowering you to craft unique content experiences for your users.

Prerequisites

Before we dive in, ensure you have:

  • A local WordPress development environment (e.g., Local by Flywheel, Docker, MAMP/WAMP).
  • Node.js and npm installed.
  • Basic familiarity with React.js and JavaScript ESNext syntax.

Step 1: Setting Up Your Development Environment

WordPress provides an official command-line tool, @wordpress/create-block, which is the easiest way to scaffold a new block. Navigate to your WordPress installation’s wp-content/plugins/ directory in your terminal and run:

npx @wordpress/create-block your-custom-block-name

Replace your-custom-block-name with your desired block slug. This command generates a complete plugin structure with all the necessary files and build scripts.

Step 2: Understanding the Block Structure

The create-block tool sets up a plugin with a dedicated folder for your block. Key files include:

  • your-custom-block-name.php: The main plugin file, responsible for registering the block on the server-side.
  • src/block.json: The metadata file for your block, defining its name, title, category, attributes, and more.
  • src/index.js: The entry point for your block’s JavaScript, importing edit.js and save.js.
  • src/edit.js: Contains the React component responsible for how your block appears and functions within the editor.
  • src/save.js: Defines the React component that determines the static HTML output of your block on the front end.
  • src/editor.scss & src/style.scss: SCSS files for editor-specific and front-end styles, respectively.

Step 3: Developing the Edit Component (src/edit.js)

The edit.js file defines the interactive interface users see in the Gutenberg editor. Let’s make a simple block that allows text input.

import { useBlockProps, RichText } from '@wordpress/block-editor';
import './editor.scss';

export default function Edit( { attributes, setAttributes } ) {
    const blockProps = useBlockProps();
    const onChangeContent = ( newContent ) => {
        setAttributes( { content: newContent } );
    };

    return (
        <p { ...blockProps }>
            <RichText
                tagName="span"
                value={ attributes.content }
                onChange={ onChangeContent }
                placeholder="Enter your custom block content..."
            />
        </p>
    );
}

Here, useBlockProps provides essential attributes for the block’s root element. RichText is a core component for editable content.

Step 4: Defining the Save Component (src/save.js)

The save.js file dictates the static HTML structure that will be saved to the database and rendered on the front end of your website.

import { useBlockProps, RichText } from '@wordpress/block-editor';

export default function Save( { attributes } ) {
    const blockProps = useBlockProps.save();
    return (
        <p { ...blockProps }>
            <RichText.Content tagName="span" value={ attributes.content } />
        </p>
    );
}

Notice RichText.Content – it renders the saved content statically.

Step 5: Registering Attributes (src/block.json)

For our example to work, we need to define the content attribute in src/block.json:

{
    "$schema": "https://schemas.wp.org/trunk/block.json",
    "apiVersion": 2,
    "name": "create-block/your-custom-block-name",
    "title": "Your Custom Block",
    "category": "widgets",
    "icon": "smiley",
    "description": "An example custom Gutenberg block.",
    "textdomain": "your-custom-block-name",
    "editorScript": "file:./index.js",
    "editorStyle": "file:./index.css",
    "style": "file:./style-index.css",
    "attributes": {
        "content": {
            "type": "string",
            "source": "html",
            "selector": "span"
        }
    }
}

The attributes section defines the data your block will store. source: "html" and selector: "span" tell Gutenberg to extract the content from a <span> tag.

Step 6: Building and Deploying Your Block

After making your changes, navigate to your block’s directory (e.g., wp-content/plugins/your-custom-block-name/) in the terminal and run:

npm start

This command compiles your JavaScript and SCSS files. For production, use npm run build. Once compiled, log into your WordPress admin, go to “Plugins,” and activate “Your Custom Block.”

Now, when you edit a post or page, you can search for “Your Custom Block” in the block inserter and add it to your content.

Conclusion

You’ve successfully built your first custom Gutenberg block! This foundational knowledge opens the door to creating highly tailored and interactive content components. From here, you can explore more advanced features like custom controls, dynamic blocks, inner blocks, and integrating with external APIs. Dive deeper into the official Gutenberg documentation to unlock the full potential of custom block development.

Leave a Reply