TechEarl

Register a Custom Gutenberg Block with block.json

The modern way to register a custom Gutenberg block: a block.json metadata file, register_block_type( __DIR__ . '/build/callout' ) on the init hook, and a @wordpress/scripts build step. Plus dynamic blocks rendered in PHP with render_callback or the block.json render file.

Ishan KarunaratnePublished ⏱️ 13 min readUpdated
Share thisCopied
Register a custom Gutenberg block with block.json and register_block_type(), build it with @wordpress/scripts, and render dynamic blocks with render_callback.

To register a custom Gutenberg block the modern way, you describe it once in a block.json file and hand that folder to register_block_type() on the init hook. WordPress reads the metadata, wires up the editor and front-end assets, and registers the type for both PHP and JavaScript from that single file. Here is the smallest complete example, a static "callout" block in the te namespace. Further down, the same setup becomes a dynamic block rendered in PHP for output that has to stay current.

The block.json (this lives next to your built JS, at build/callout/block.json):

json
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "te/callout",
  "version": "1.0.0",
  "title": "Callout",
  "category": "text",
  "icon": "megaphone",
  "description": "A simple highlighted callout box.",
  "textdomain": "te-block",
  "editorScript": "file:./index.js",
  "editorStyle": "file:./index.css",
  "style": "file:./style-index.css"
}

And the PHP that registers it:

php
<?php
/**
 * Plugin Name: TE Block
 * Plugin URI:  https://techearl.com/wordpress-custom-gutenberg-block-block-json
 * Description: A custom Gutenberg block registered from block.json metadata.
 * Version:     1.0.0
 * Author:      Ishan Karunaratne
 * Author URI:  https://techearl.com
 * License:     GPL-2.0-or-later
 * Text Domain: te-block
 */

add_action( 'init', 'te_register_blocks' );

function te_register_blocks() {
    register_block_type( __DIR__ . '/build/callout' );
}

That is the whole registration. register_block_type() gets a directory path, finds the block.json inside it, and does the rest. No wp_enqueue_script, no hand-written asset handles, no duplicate block definition in JavaScript.

Why a directory path works

Passing a folder to register_block_type() is the part that surprises people coming from older tutorials. Since WordPress 5.8 (July 2021), the function's first parameter accepts the path to the directory that holds a block.json. WordPress opens that file, reads the name, resolves every file:-prefixed asset relative to the JSON, enqueues them in the right context, and registers the type. The block.json is the canonical block registration mechanism in WordPress as of 5.8, and everything else hangs off it.

The file: convention is the glue. An asset field like "editorScript": "file:./index.js" tells WordPress "the script is the index.js sitting next to this file." WordPress also reads the matching index.asset.php that the build step emits (the dependency and version manifest) so the script declares its @wordpress/* dependencies automatically. You never type out a handle or a version string.

A few fields earn their keep:

  • apiVersion is the Block API contract, not your plugin version. Use 3 (introduced in WordPress 6.3, it opts the block's editor markup into the iframe-isolated canvas). 2 is still valid and is the right floor if you must support editors before 6.3. 1 is legacy; do not start there.
  • name must be namespace/block-name. The namespace is yours: I use te/ here so the block is unambiguously mine and will not collide with core/ or another plugin's blocks.
  • category is one of the editor's inserter groups (text, media, design, widgets, theme, embed), or a custom one you register separately.
  • editorScript / editorStyle load only inside the editor. style loads in both the editor and the front end. script (front-end JS) loads in both as well; a static block usually needs none.

The build step with @wordpress/scripts

The block.json points at build/callout/index.js, but you do not write that file by hand. You write modern JSX in src/ and let @wordpress/scripts (the wp-scripts toolchain) compile it. It wraps webpack and Babel with the WordPress defaults already configured, so there is no config file to babysit.

A minimal package.json:

json
{
  "name": "te-block",
  "version": "1.0.0",
  "scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start"
  },
  "devDependencies": {
    "@wordpress/scripts": "^27.0.0"
  }
}

Then:

bash
npm install
npm run build

wp-scripts build reads src/index.js as the entry point, compiles the JSX and SCSS, and writes the production bundle plus an index.asset.php manifest into build/. It also copies your src/block.json into build/ so the file: paths resolve against the compiled assets, which is exactly why the PHP points at build/callout and not src. During development, npm run start does the same thing in watch mode with source maps, rebuilding on every save.

If you are scaffolding from scratch, npx @wordpress/create-block te-callout generates this entire layout (a working block.json, src files, package.json, and the PHP plugin header) in one command. It is the fastest way to get a correct skeleton, and the structure it produces is the structure above.

edit.js and save.js: the two halves of a static block

A block has two faces. edit renders what the author sees and manipulates in the editor; save returns the static markup that gets serialized into the post's post_content and shipped to visitors. For a static block, save returns real HTML that lives in the database, so no PHP runs at render time on the front end.

The entry point ties them together:

javascript
import { registerBlockType } from '@wordpress/blocks';
import metadata from './block.json';
import Edit from './edit';
import save from './save';
import './style.scss';

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

edit.js, a single editable paragraph using the editor's rich-text control:

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

export default function Edit( { attributes, setAttributes } ) {
	const blockProps = useBlockProps( { className: 'te-callout' } );

	return (
		<RichText
			{ ...blockProps }
			tagName="p"
			value={ attributes.content }
			onChange={ ( content ) => setAttributes( { content } ) }
			placeholder="Write your callout..."
		/>
	);
}

save.js, the markup written to the database:

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

export default function save( { attributes } ) {
	const blockProps = useBlockProps.save( { className: 'te-callout' } );

	return <RichText.Content { ...blockProps } tagName="p" value={ attributes.content } />;
}

You also declare the content attribute so the value persists. Add it to block.json:

json
{
  "attributes": {
    "content": {
      "type": "string",
      "source": "html",
      "selector": "p"
    }
  }
}

The source and selector tell WordPress to parse the saved value back out of the <p> when it re-loads the block in the editor, which is how the editor reconstructs state from the static HTML on the next edit. I keep RichText.Content in save and RichText in edit deliberately: mismatched markup between the two is the single most common cause of a block validation error.

For a block that should render through PHP at request time instead of freezing HTML into the post (a latest-posts list, anything that depends on live data), save returns null and PHP produces the markup. That is a dynamic block, covered in the next section.

Dynamic block with render_callback

A dynamic block renders its front-end markup in PHP on every request instead of saving fixed HTML into post_content. The block stores only its attributes, and a PHP callback rebuilds the HTML from current data each time the page is viewed.

A static block is right when the output is fixed at save time. It goes stale for anything that is supposed to change after you save: a "latest 5 posts" block saved as HTML lists the five latest posts from the day you placed it, forever, and the editor cannot tell because the saved HTML still validates. Use a dynamic block when:

  • The output depends on data that changes after save (recent posts, comment counts, stock levels).
  • The output depends on the request itself (the logged-in user, the current date, a query string).
  • You want to change the markup later by editing PHP, not by re-saving every post that uses the block.

The trade-off is that the work happens on each page load, so a heavy query inside a dynamic block wants a transient or object cache in front of it. A full-page cache still covers most of the cost for anonymous visitors.

The block.json render property

The modern wiring, added in WordPress 6.1 (November 2022), is a render field pointing at a PHP file:

json
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "te/latest-posts",
  "title": "TE Latest Posts",
  "category": "widgets",
  "attributes": {
    "count": { "type": "number", "default": 5 }
  },
  "editorScript": "file:./index.js",
  "render": "file:./render.php"
}

Inside render.php, $attributes, $content and $block are already in scope, and the file is the output buffer, so you echo:

php
<?php
// render.php runs on every front-end request for this block.
$count = isset( $attributes['count'] ) ? absint( $attributes['count'] ) : 5;

$query = new WP_Query( array(
    'posts_per_page'      => $count,
    'post_status'         => 'publish',
    'no_found_rows'       => true,
    'ignore_sticky_posts' => true,
) );

if ( ! $query->have_posts() ) {
    return;
}

echo '<ul ' . get_block_wrapper_attributes() . '>';
while ( $query->have_posts() ) {
    $query->the_post();
    printf(
        '<li><a href="%1$s">%2$s</a></li>',
        esc_url( get_permalink() ),
        esc_html( get_the_title() )
    );
}
echo '</ul>';

wp_reset_postdata();

render_callback in register_block_type

render_callback is the original mechanism, an argument to register_block_type() available since WordPress 5.0, and what the render file resolves to under the hood. Without a render.php, register the callback directly and return the markup as a string:

php
add_action( 'init', function () {
    register_block_type( __DIR__ . '/build', array(
        'render_callback' => 'te_render_latest_posts',
    ) );
} );

/**
 * @param array    $attributes The block's saved attribute values.
 * @param string   $content    Inner block markup (empty for most dynamic blocks).
 * @param WP_Block $block      The block instance (context, name, parsed attrs).
 */
function te_render_latest_posts( $attributes, $content, $block ) {
    $count = isset( $attributes['count'] ) ? absint( $attributes['count'] ) : 5;

    $query = new WP_Query( array(
        'posts_per_page'      => $count,
        'post_status'         => 'publish',
        'no_found_rows'       => true,
        'ignore_sticky_posts' => true,
    ) );

    if ( ! $query->have_posts() ) {
        return '';
    }

    $items = '';
    while ( $query->have_posts() ) {
        $query->the_post();
        $items .= sprintf(
            '<li><a href="%1$s">%2$s</a></li>',
            esc_url( get_permalink() ),
            esc_html( get_the_title() )
        );
    }
    wp_reset_postdata();

    return sprintf(
        '<ul %1$s>%2$s</ul>',
        get_block_wrapper_attributes(),
        $items
    );
}

The three arguments: $attributes is the saved attribute array, $content is inner-block markup (empty for a leaf block like this, useful for containers), and $block is the WP_Block instance with context and parsed attributes. The third parameter arrived in WordPress 5.5, so older callbacks declare only two; you can declare just $attributes if that is all you need.

Escape at the point of output: esc_url() for hrefs, esc_html() for text, esc_attr() for attribute values, and absint() to clamp a numeric attribute before it touches a query. Never interpolate a raw attribute into HTML. get_block_wrapper_attributes() emits the wrapper's class and style with the editor-chosen alignment and color classes folded in, already escaped.

Editor preview with ServerSideRender

With no saved markup, save returns null, and the editor previews the real PHP output through @wordpress/server-side-render:

javascript
import { registerBlockType } from '@wordpress/blocks';
import ServerSideRender from '@wordpress/server-side-render';
import { useBlockProps } from '@wordpress/block-editor';
import metadata from './block.json';

registerBlockType( metadata.name, {
    edit( { attributes } ) {
        const blockProps = useBlockProps();
        return (
            <div { ...blockProps }>
                <ServerSideRender
                    block={ metadata.name }
                    attributes={ attributes }
                />
            </div>
        );
    },
    save() {
        return null;
    },
} );

ServerSideRender posts the block name and current attributes to the REST API, the server runs your render code, and the editor shows the result; change the count in the inspector and it re-fetches. Because every attribute change hits the server, some developers render a JS approximation for fast-moving controls and keep ServerSideRender for the server-only parts.

Verify a dynamic block

  • Editor: you should see the live server preview. A "this block contains unexpected or invalid content" error almost always means save is returning markup instead of null.
  • Front end: add a new post and reload; the list should change without re-saving the page that holds the block.
  • Database: the saved block in post_content should be only the delimiter and attributes (<!-- wp:te/latest-posts {"count":5} /-->). Saved inner HTML means the block is not actually dynamic.
  • REST: if the preview is blank, check the Network tab for /wp/v2/block-renderer/te/latest-posts. A 401 or 403 usually means a current-user permission problem; a 500 means your PHP threw.

Why block.json beats registering in JavaScript alone

The old approach called registerBlockType() in JavaScript with the full block definition inline, and enqueued the editor script from PHP by hand. It works, but the block exists only in the browser. PHP has no idea the block is there. That cripples a few things that matter:

  • Server awareness. With block.json, both PHP and JS register the same type from the same metadata. The REST API exposes it, server-side block patterns can reference it, and WP_Block_Type_Registry knows about it. The JS-only block is invisible to all of that.
  • Asset handling. The file: fields plus the generated index.asset.php mean WordPress enqueues your scripts and styles in the correct context with correct dependencies and cache-busting versions. Doing that by hand means maintaining wp_enqueue_script calls that drift out of sync with the build.
  • Internationalization. textdomain in block.json lets WordPress set up script translations for your block automatically. The JS-only path makes you wire wp_set_script_translations() yourself.
  • One source of truth. Block name, category, icon, attributes, and supports live in one file that both runtimes read. The JS-only version splits that across a JS object and ad hoc PHP, and they fall out of step the first time someone edits one and not the other.

The practical summary: registering in JS alone still renders a block, but it is a client-only object that the rest of WordPress cannot see. The metadata file makes the block a first-class citizen on both sides of the request.

Verify the block is registered

After npm run build and activating the plugin, open any post in the editor and click the inserter (the +). Search for "Callout." The block should appear under the Text group with the megaphone icon, and inserting it should give you the editable paragraph. Type into it, save the post, and view the front end: you should see your text wrapped in the <p class="te-callout"> that save returned, styled by style-index.css.

If it does not show up, the usual suspects are: the plugin is not active, you pointed register_block_type() at src instead of build (so the compiled block.json and assets are not where PHP is looking), or the build failed and build/callout/block.json does not exist. A quick check from WP-CLI confirms registration server-side:

bash
wp eval 'var_dump( WP_Block_Type_Registry::get_instance()->is_registered( "te/callout" ) );'

A bool(true) there means PHP sees the block, which isolates any remaining problem to the editor JavaScript (check the browser console for a build or validation error).

WordPress 5.8 (July 2021) is the floor. That release made register_block_type() accept a path to the folder containing the block.json file, which is what the metadata-first approach relies on.

If you set apiVersion to 3, you also need WordPress 6.3 or newer, since that is when API version 3 (the iframe-isolated editor canvas) was introduced. Use 2 as the floor if you must support 5.8 through 6.2.

For anything using JSX, yes. The browser cannot run JSX directly, so @wordpress/scripts compiles your src/ files into a plain-JS bundle plus the index.asset.php dependency manifest that WordPress reads.

You can technically write the editor script in vanilla wp.blocks.registerBlockType() calls with no build, but you give up JSX, automatic dependency extraction, and the convenience that makes block development bearable. I always run the build.

At build. The wp-scripts build step copies your block.json into build/ alongside the compiled index.js, index.css, and the asset manifest, so the file: paths in the metadata resolve against the compiled output.

Pointing at src finds the source block.json but its file: references point at uncompiled JSX the browser cannot run, so the block silently fails to load in the editor.

editorScript and editorStyle load only inside the block editor. style loads in both the editor and the front end, which is where your block's visible CSS belongs. script is front-end JavaScript and loads in both contexts too.

A static block usually needs only editorScript (the edit/save logic) and style (the shared CSS). You rarely need a front-end script unless the block has interactive behavior for visitors.

Use a static block when the output is fixed at save time: a callout, a styled quote, a layout wrapper. The HTML save returns is frozen into post_content and served as-is, with no PHP at render time.

Use a dynamic block when the output depends on live data (recent posts, the current user, a query that changes after the post is saved). There, save returns null and a PHP render_callback builds the markup on each request. See the dynamic block section for that pattern.

They do the same job: name PHP that produces the block's front-end HTML at request time. render_callback is the original argument to register_block_type(), available since WordPress 5.0. The render property in block.json (a file:./render.php path) is the declarative form, added in WordPress 6.1, and is usually the cleaner choice on a modern install.

Because a dynamic block deliberately saves no markup into post_content. Returning null tells the editor there is nothing static to store or validate. If save returns HTML, it gets frozen into the post and you will usually get a block-validation error later.

See also

Sources

Authoritative references this article was fact-checked against.

TagsWordPressGutenbergBlock EditorJavaScriptblock.jsonPHPrender_callback

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Learn Docker Compose with a working docker-compose.yml: services, volumes, networks and service-name DNS, bridge vs host networking, and host.docker.internal.

Docker Compose: Getting Started with docker-compose.yml

A working docker-compose.yml that runs a web app and a database together, the commands you need (up, down, logs, exec), how containers find each other on Docker networks, passing environment variables (ARG vs ENV, -e, env_file), and the V1-to-V2 change that breaks a lot of older tutorials.