Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 68 ยท REST API, AJAX and Blocks

Building Blocks: An Overview

Learn how WordPress blocks are built - block.json, registerBlockType, edit and save, attributes, create-block, InnerBlocks, block supports and why deprecations exist.

Everything in the block editor is a block: a paragraph, an image, a column layout, a button. Themes can ship blocks, plugins can ship blocks, and you can write your own. A block is a small package with three parts: a JSON file that describes it, a JavaScript component that shows it in the editor, and either a second JavaScript function or a PHP function that decides what it looks like on the front end.

This lesson is a map, not a full course. You will see the files in a typical block, what attributes are, how the editor stores a block inside the post content, and the tools that set a project up for you. The next lesson covers dynamic blocks and block bindings, where PHP renders the output.

WordPress and its build tools cannot run on this site. The block files below (JSON, JavaScript, PHP) are real code shown read-only. The runnable examples are plain-PHP stand-ins that reproduce one idea: how block attributes become the HTML comments stored in the database.

What a block really is in the database

When you save a post, the editor serializes the blocks into ordinary text in post_content. Blocks are wrapped in HTML comments, so a post is still valid HTML for any system that does not know about blocks:

HTML
<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">Hello from a block.</p>
<!-- /wp:paragraph -->

The comment holds the block name (core/paragraph is written as paragraph) and a JSON object of attributes. The HTML in between is what the block's save function produced. A block with nothing to save, or one that is rendered by PHP, closes itself: <!-- wp:latest-posts {"postsToShow":3} /-->.

flowchart LR
    A["Editor: edit() component"] --> B["Attributes in JavaScript"]
    B --> C["save() output + comment JSON"]
    C --> D["post_content in wp_posts"]
    D --> E["Front end prints the HTML"]
    D --> A

The editor works with attributes; the database stores comment-wrapped HTML; loading a post parses that text back into attributes.

The files of a block

A project made by the official starter has a folder like this:

TEXT
my-callout/
  package.json
  my-callout.php
  src/
    block.json
    index.js
    edit.js
    save.js
    editor.scss
    style.scss
  build/        (generated)

block.json

block.json is the single source of truth. WordPress reads it on the PHP side to register the block and on the JavaScript side to know its settings.

JSON
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "myplugin/callout",
  "version": "1.0.0",
  "title": "Callout",
  "category": "text",
  "icon": "megaphone",
  "description": "A highlighted note with a tone.",
  "textdomain": "myplugin",
  "attributes": {
    "tone": { "type": "string", "enum": ["info", "warning"], "default": "info" },
    "message": { "type": "string", "source": "html", "selector": "p" }
  },
  "supports": {
    "html": false,
    "color": { "background": true, "text": true },
    "spacing": { "padding": true },
    "typography": { "fontSize": true }
  },
  "editorScript": "file:./index.js",
  "editorStyle": "file:./index.css",
  "style": "file:./style-index.css"
}

The block name is namespace/name, where the namespace is yours (use your plugin or company slug, never core). Each attribute has a type and may have a default, an enum of allowed values, or a source that tells the editor to read the value from the saved HTML instead of from the comment. Here message is read from the <p> inside the markup, while tone is kept in the comment JSON.

Registering it

On the PHP side, one call registers everything that block.json declares:

PHP
<?php
// my-callout.php (real WordPress, read-only)
add_action( 'init', function (): void {
    register_block_type( __DIR__ . '/build' );
} );

On the JavaScript side, the editor script registers the block's components:

JavaScript
// src/index.js (read-only)
import { registerBlockType } from '@wordpress/blocks';
import metadata from './block.json';
import Edit from './edit';
import save from './save';

registerBlockType( metadata.name, {
    edit: Edit,
    save,
} );

edit and save

edit is a React component that draws the block inside the editor. It receives attributes and setAttributes:

JSX
// src/edit.js (read-only)
import { useBlockProps, RichText, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, SelectControl } from '@wordpress/components';

export default function Edit( { attributes, setAttributes } ) {
    const { tone, message } = attributes;
    const blockProps = useBlockProps( { className: 'is-tone-' + tone } );

    return (
        <>
            <InspectorControls>
                <PanelBody title="Tone">
                    <SelectControl
                        value={ tone }
                        options={ [
                            { label: 'Info', value: 'info' },
                            { label: 'Warning', value: 'warning' },
                        ] }
                        onChange={ ( value ) => setAttributes( { tone: value } ) }
                    />
                </PanelBody>
            </InspectorControls>
            <div { ...blockProps }>
                <RichText
                    tagName="p"
                    value={ message }
                    onChange={ ( value ) => setAttributes( { message: value } ) }
                    placeholder="Write a note..."
                />
            </div>
        </>
    );
}

save is a plain function that returns the final markup. It must be pure: the same attributes must always give the same HTML, and it cannot use hooks or fetch data.

JSX
// src/save.js (read-only)
import { useBlockProps, RichText } from '@wordpress/block-editor';

export default function save( { attributes } ) {
    const blockProps = useBlockProps.save( { className: 'is-tone-' + attributes.tone } );
    return (
        <div { ...blockProps }>
            <RichText.Content tagName="p" value={ attributes.message } />
        </div>
    );
}

The JSX syntax is covered in the React tutorial; the block editor itself is built with React, so knowing its basics helps.

Starting a block project

You rarely write these files by hand. The official scaffold tool creates the whole folder, the PHP plugin file, and the build setup:

Terminal
npx @wordpress/create-block@latest my-callout
cd my-callout
npm start       # watch mode while you develop
npm run build   # production files in build/

Behind it, @wordpress/scripts is a package that bundles webpack, Babel and linting with sensible defaults, so a block needs no hand-written build config. Another option is wp-env, a Docker-based local WordPress, from the lesson on setting up a local site.

Block supports

Instead of building color pickers and padding controls yourself, you turn them on with the supports key in block.json. WordPress then adds the controls to the sidebar, stores the choices and writes the matching classes or inline styles onto the element that carries useBlockProps. Common supports include align, color, spacing, typography, border, anchor and html (set it to false to hide the "Edit as HTML" option). Supports are the reason a new block feels consistent with core blocks, and they connect to the design tokens in theme.json.

InnerBlocks: blocks inside blocks

Some blocks are containers: Group, Columns, Quote. They use InnerBlocks to let editors nest other blocks inside.

JSX
// edit.js (read-only)
import { useBlockProps, useInnerBlocksProps } from '@wordpress/block-editor';

export default function Edit() {
    const blockProps = useBlockProps();
    const innerBlocksProps = useInnerBlocksProps( blockProps, {
        allowedBlocks: [ 'core/heading', 'core/paragraph', 'core/button' ],
        template: [ [ 'core/heading', { level: 3 } ], [ 'core/paragraph' ] ],
    } );
    return <div { ...innerBlocksProps } />;
}

In save, you render the children with <InnerBlocks.Content /> (or useInnerBlocksProps.save). In the stored markup, the children appear between the parent's opening and closing comments. allowedBlocks limits what can go inside, and template pre-fills the container with a starting layout.

Deprecations: why changing save is risky

When a post loads, the editor runs your current save function on the stored attributes and compares the result with the HTML in the database. If they differ, the editor shows "This block contains unexpected or invalid content" and offers recovery. So any change to save output, even adding a class, breaks every existing post that used the old markup.

The fix is the deprecated array. You keep the old attributes and the old save, and WordPress tries each deprecated version when the current one does not match, then migrates the block to the new format the next time the post is saved. Remember the rule: changing what save prints needs a deprecation, while blocks rendered in PHP avoid the problem because they store nothing. The next lesson looks at that style.

Try it: attributes to block markup

This stand-in implements the serialization rules above. Attributes with a source stay out of the comment, defaults are omitted, and only the comment JSON gets WordPress's special escaping for --, <, > and &. Nested blocks go between the opening and closing comments. It is not WordPress's real serializer, which also handles innerContent arrays and more.

PHP Serialize blocks to comment markup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice what is missing: the message and content values never appear in any comment, and the third block has no JSON at all because its tone equals the default. The last block shows the escaping, and because it has no HTML it closes itself.

Try it: filling defaults and validating attributes

When the editor loads a block it also needs the reverse step: turn whatever is stored into a complete, valid attribute set. This stand-in applies the type, enum and default rules from block.json.

PHP Normalize block attributes against a schema

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Common mistakes

  • Editing save without a deprecation. Existing posts show an invalid-content notice.
  • Using core/ as your namespace. Pick your own, such as myplugin/callout.
  • Putting data fetching or randomness in save. It must be a pure function of the attributes; use a PHP render instead.
  • Forgetting useBlockProps. Without it the wrapper loses the editor's classes, supports and selection behavior.
  • Hand-writing the build. Start from create-block and @wordpress/scripts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does the block editor store a block's saved markup and attributes?

    Blocks are serialized into the post's content as comment-wrapped HTML, so older systems still see valid HTML.
  2. 2. An attribute in block.json has "source": "html" and a selector. Where is its value stored?

    Sourced attributes are parsed from the saved markup, so they are not repeated in the comment's JSON.
  3. 3. You add a new CSS class to the output of a block's save function. What happens to old posts?

    The editor compares the stored HTML with what the current save produces. A mismatch needs a deprecation entry that keeps the old save.
  4. 4. What is the purpose of the supports key in block.json?

    Supports add standard sidebar controls and the matching classes or styles without writing the UI yourself.
  5. 5. Which tool scaffolds a block project with a build setup?

    create-block generates the plugin file, block.json, the source files and an @wordpress/scripts based build.

Summary

  • A block is described by block.json, edited with an edit component and printed by save (static) or PHP (dynamic).
  • Blocks are stored in post_content as HTML comments with JSON attributes; sourced attributes live in the HTML instead.
  • register_block_type() in PHP and registerBlockType() in JavaScript connect the metadata to the components.
  • Block supports add standard controls; InnerBlocks lets a block contain other blocks.
  • Changing the output of save breaks stored posts unless you add a deprecation.
  • Use @wordpress/create-block and @wordpress/scripts instead of a hand-built toolchain.
  • The runnable examples are plain-PHP stand-ins for the serialization rules, not WordPress code.

Next: Dynamic Blocks and Block Bindings