WordPress block tutorial

The Hello World Block – Create a custom WordPress Gutenberg Block

Basics of the registerBlockType function

In this article we will focus on the basics of what a block is and how they are registered. We will not cover how to set up your environment and project for block development. We will do this in a later post!

You register a block in javascript with the function registerBlockType (found in ‘@wordpress/blocks’). The function takes a name and a block object as parameters. The block object basically contains:

  1. Meta data. This includes name, category and attributes that the block will use.
  2. Edit function. A React functional component that is run in the editor when you create your pages and posts.
  3. Save function. A React functional component that is run when you click on save. WordPress will save the html that is returned from this function into the database with your post.

Both the save & edit functions return jsx. Below we register a ‘Hello World’ block:

import { registerBlockType } from '@wordpress/blocks';

registerBlockType("your-namespace/helloworld", {
  category: "helloworld",
  attributes: {},
  title: 'Hello World',
  icon: 'block-default',
  keywords: ['sample-block', 'hello world'],
  edit: (props) => {
    const { attributes, setAttributes } = props; // you will use these!
    return (
          Hello World (in the editor)!
  save: (props) => {
    const { attributes } = props; // you will use these!
    return (
        Hello World!

For this block to actually be useful we will need to add editing capabilities. This is done by either adding inline-editing with the ‘toolbar’ or adding editing controls on the right sidebar. Here is a short intro to coding the inspector controls (adding controls to the editor sidebar).

When you create larger blocks, you will put the edit & save function in seperate files and import them when you register your block registration. That is why you will find edit.js & save.js snippets in other tutorials on Wpblockz.

To get a block to show up in the editor, you will have to register the scripts with php. We will cover the setup of your first block in our next post. You can also check the official docs here: https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/writing-your-first-block-type/. Sign up to our newsletter below to get the latest tops on WordPress Gutenberg blocks!

Read more tutorials

Stay updated with the latest from WpBlockz

* indicates required