Creating Your First WordPress Block

The WordPress block editor, known as Gutenberg, offers a modern and intuitive interface for managing content. It’s based on the concept of “blocks”, which are modular elements that users can insert, rearrange, and style to build content-rich web pages. In this guide, we’ll walk you through how to create your first WordPress block programmatically with code.

Prerequisites:

Before you start, you should have:

  • A local or remote WordPress installation.
  • Basic understanding of JavaScript, PHP, React, and WordPress development.

For creating a custom block, you’ll need a modern development setup for JavaScript. That means setting up Node.js and npm (Node Package Manager) on your machine. We’ll also use wp-scripts package provided by WordPress to simplify the build process.

Step 1: Setup a Plugin

Blocks are typically distributed as plugins. So, start by creating a new plugin. In your WordPress plugin directory (usually wp-content/plugins/), create a new folder, say, my-first-block.

Inside the plugin directory, create two files:

  • my-first-block.php: This is the main plugin file.
  • index.js: This is where we’ll write our block code.

Step 2: Enqueue Block Assets

Next, we need to enqueue the JavaScript file we’ll be writing. In my-first-block.php, add the following:

<?php
/**
 * Plugin Name: My First Block
 */

function my_first_block_script() {
    wp_enqueue_script(
        'my-first-block',
        plugins_url( 'index.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element' ),
        time() // For development only, replace with your plugin version for production
    );
}

add_action( 'enqueue_block_editor_assets', 'my_first_block_script' );

Step 3: Install Node.js and npm

Now you need to setup Node.js and npm (Node Package Manager). You can download Node.js from the official website. npm is bundled with Node.js.

Once you’ve installed Node.js and npm, check their versions by running these commands in your terminal:

node -v
npm -v

Step 4: Install the wp-scripts package

In the terminal, navigate to your plugin’s directory (my-first-block) and initiate a new npm project with npm init -y.

Next, install the @wordpress/scripts package by running the command:

npm install @wordpress/scripts --save-dev

Then, create a new file in your plugin directory called webpack.config.js:

const defaultConfig = require( "@wordpress/scripts/config/webpack.config" );

module.exports = {
  ...defaultConfig,
};

Step 5: Create a Block

Now, let’s write some JavaScript to create a simple block. In index.js, add the following code:

const { registerBlockType } = wp.blocks;
const { RichText } = wp.blockEditor;

registerBlockType('my-first-block/hello-world', {
    title: 'Hello World',
    icon: 'admin-site',
    category: 'common',
    attributes: {
        content: {
            type: 'string',
            default: 'Hello World',
        },
    },
    edit({attributes, setAttributes}) {
        const { content } = attributes;
        function onChangeContent(newContent) {
            setAttributes({ content: newContent });
        }

        return (
            <RichText
                tagName="p"
                value={content}
                onChange={onChangeContent}
            />
        );
    },
    save({attributes}) {
        return (
            <RichText.Content tagName="p" value={attributes.content} />
        );
    },
});

This code registers a new block type and makes it available in the block editor. The block includes an editable field that allows users to input text.

Step 6: Build and Test Your Block

In your package.json, add a new scripts property:

"scripts": {
    "start": "wp-scripts start",
    "build": "wp-scripts build"
}

Run the development build command:

npm run start

If everything is set up correctly, your block should be available in the Gutenberg editor under the name ‘Hello World’. Test your block by creating a new post and adding the ‘Hello World’ block.

And voilà! You’ve created your first WordPress block programmatically with code.

Remember, the world of Gutenberg blocks is vast, and there are a multitude of options and attributes you can utilize to create more complex and dynamic blocks. But this simple guide should help you get started on your path to mastering WordPress block development. Happy coding!


Special thanks to Code Block Pro – for amazing syntax highlighter plugin.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *