WPGEARED2.0.
WordPress Development

Create a custom Gutenberg block with block.json

Published
Share Report:

Create a native Gutenberg block by declaring its metadata in block.json, providing its editor and save functions, and registering the built metadata from PHP. Use @wordpress/create-block to start the project, then build its source files before activating it in WordPress.

You will build a notice with one editable text field. It needs no ACF or other block-builder plugin, but a small plugin still packages the block. “Without a block-builder plugin” does not mean “without any plugin.”

The main version saves HTML with the post. A separate conversion later shows how PHP can render the same message dynamically.

1. Prepare a local development site

Use a local or staging WordPress installation, terminal access and a backup. You need Node.js and npm for the JavaScript build. The current create-block documentation requires Node.js 22.13.0 or newer, checked November 2026.

Use a supported WordPress release for development. The example uses Block API version 3, introduced in WordPress 6.3, according to the metadata reference checked November 2026. That API minimum is not a compatibility guarantee for newer build tools. Keep any higher minimum declared by your generated project.

There are two separate jobs here. PHP registers the block with WordPress. JavaScript provides its editing and serialization behavior. A successful PHP registration does not prove the editor bundle built or that a saved block reloads without errors.

2. Scaffold the plugin, then use one explicit source layout

From the local site's wp-content/plugins directory, run:

npx @wordpress/create-block@latest wpgeared-notice --namespace wpgeared
cd wpgeared-notice

This scaffolds the plugin and sets up its build dependencies. Let the command finish successfully before editing its files. Generated layouts can change between create-block releases. This guide uses an explicit single-block layout rather than assuming every release generates the same folders.

Before replacing files, keep a copy of the generated project outside WordPress's plugins directory. Move its original src directory into that backup, then create the src files shown below. Replace the generated main plugin's registration code rather than adding a second registration beside it. Do not leave another starter block under src and accidentally build both.

Retain the generated package.json dependencies. Set its two script values to:

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

This is a fragment to merge into package.json, not a replacement for the whole file. Keep its other fields and dependency declarations. If dependency installation was interrupted, run npm install from this project directory and resolve its errors before continuing.

The intended editable structure is:

wpgeared-notice/
├── wpgeared-notice.php
├── package.json
└── src/
    ├── block.json
    ├── index.js
    ├── edit.js
    ├── save.js
    └── style.scss

If your generated main PHP file uses a different name, use that file rather than leaving two plugin headers in the directory. Preserve any stricter generated PHP or WordPress requirement headers when replacing its contents with the small registration example below.

3. Define the block and its attribute

Put this in src/block.json:

{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "wpgeared/notice",
  "version": "1.0.0",
  "title": "WPGeared Notice",
  "category": "text",
  "icon": "info",
  "description": "A notice with one editable plain-text message.",
  "textdomain": "wpgeared-notice",
  "attributes": {
    "message": { "type": "string", "default": "Read this before continuing." }
  },
  "supports": { "html": false },
  "editorScript": "file:./index.js",
  "style": "file:./style-index.css"
}

The name wpgeared/notice is the stable identifier, while the title is what editors see in the inserter. Prefixing the name avoids competing with another block named simply “notice.”

message is a string attribute with a default. It has no source or selector, so WordPress stores its value in the block's comment data rather than extracting it from a particular HTML element. The later dynamic version can then use the same attribute storage. The attributes reference describes both approaches.

The file: asset paths are relative to the metadata file. With this single-block layout, the build places the metadata and generated assets together in build. editorScript identifies the editor registration bundle. style identifies the shared stylesheet. This small example needs no separate editor-only stylesheet or front-end JavaScript.

supports.html is false to remove the block's HTML editing option. That is an editing choice, not a general security boundary. Output still needs to be safe.

4. Add the editor, save function and entry point

Put this in src/edit.js:

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

export default function Edit({ attributes, setAttributes }) {
    return (
        <div {...useBlockProps()}>
            <PlainText
                value={attributes.message}
                onChange={(message) => setAttributes({ message })}
                placeholder="Write a notice"
                aria-label="Notice message"
            />
        </div>
    );
}

useBlockProps() supplies the editor wrapper properties. PlainText displays an editable text field. Its change callback updates this block instance's message attribute, rather than a global variable shared by every notice.

Put this in src/save.js:

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

export default function save({ attributes }) {
    return <p {...useBlockProps.save()}>{attributes.message}</p>;
}

The save function returns the HTML stored in the post. useBlockProps.save() supplies the saved wrapper properties. React renders the string as text, so typing angle brackets does not turn the message into arbitrary HTML. The editor wrapper does not have to be identical to the saved wrapper, but the saved output must remain consistent with the block's serialization rules. See the edit/save reference.

Put this in src/index.js:

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 });

This connects the metadata name with the editor and save implementations. Importing the stylesheet gives the build tool a source asset to compile. The wp-scripts build documentation explains how metadata selects entry points and how an imported style.scss becomes style-index.css.

Put this in src/style.scss:

.wp-block-wpgeared-notice {
    padding: 1rem;
    border-left: 4px solid #2563eb;
    background: #eff6ff;
    color: #172554;
    overflow-wrap: anywhere;
    white-space: pre-wrap;
}

The selector belongs only to this block. It does not change every paragraph on the site. overflow-wrap handles long text, while white-space preserves line breaks from the plain-text field.

5. Register the built metadata and build the files

Use this main plugin file, retaining any higher generated requirement headers as noted above:

<?php
/**
 * Plugin Name: WPGeared Notice
 * Description: A native notice block example.
 * Version: 1.0.0
 */
defined( 'ABSPATH' ) || exit;

function wpgeared_register_notice_block() {
    register_block_type( __DIR__ . '/build' );
}
add_action( 'init', 'wpgeared_register_notice_block' );

This path is intentional: the single-block layout places block.json directly under build. If you keep a different nested layout, the PHP path must point to the directory containing that built metadata instead. Do not register a metadata collection and then separately register the same block again. WordPress's registration guide explains the server and client pieces.

Run:

npm run build

Before activation, inspect the output. For this layout, check that build contains block.json, index.js, index.asset.php and style-index.css. The generated asset file provides dependency and version information for the bundle. If any are missing, fix the build before changing the PHP registration path.

During development, use:

npm start

That watches source files and rebuilds changes. Stop it when you are done, and use the production build for the copy you distribute. Edit src, not generated build files that the next compilation will replace. Include the built files in an installed plugin. Do not upload node_modules as a substitute for building.

6. Check the static block in the editor and front end

Activate WPGeared Notice, open a test post and insert WPGeared Notice from the block inserter. Add two instances with different messages. Save, reload the editor and view the front end.

Check that both messages survive independently, punctuation is readable, the stylesheet loads and the editor shows no invalid-block warning. Test a long line on a narrow viewport as well. A build finishing without errors cannot confirm these interactions.

The static version stores its paragraph in the post. If the plugin is deactivated, that saved HTML can remain visible, but the plugin's block registration and stylesheet are no longer available. Keep that distinction in mind when deciding how to retire the component.

7. Optional: switch this experiment to PHP rendering

Do this on a disposable copy, not directly on existing published notices. Static and dynamic rendering are alternatives for this example, not two registrations of the same name.

Keep the unsourced message attribute. Add this property to src/block.json, with the necessary comma before it:

"render": "file:./render.php"

Replace src/save.js with:

export default function save() {
    return null;
}

Create src/render.php:

<?php
/** @var array $attributes */
defined( 'ABSPATH' ) || exit;
$message = isset( $attributes['message'] ) && is_string( $attributes['message'] )
    ? $attributes['message']
    : 'Read this before continuing.';
?>
<p <?php echo get_block_wrapper_attributes(); ?>><?php echo esc_html( $message ); ?></p>

The render file receives the block's attributes. It treats the message as plain text and escapes it when outputting HTML. get_block_wrapper_attributes() supplies the block wrapper's HTML attributes.

The default wp-scripts build copies PHP files named by a detected metadata file's render field. Rebuild and confirm that build/render.php exists beside the rebuilt metadata. This is different from copying every PHP file under src, which requires a separate build option. Then insert a fresh test block, save, reload and inspect its output. Existing saved static instances can require deliberate migration or reinsertion because the save behavior changed. Do not make a silent change to every live block and assume validation will sort it out.

The dynamic version's save function returns null, so it provides no saved HTML fallback. Its comment data can remain in the post after deactivation, but the visible notice depends on the registered PHP renderer. The static and dynamic rendering guide explains why the two approaches behave differently.

Troubleshoot and undo

The block is missing from the inserter: confirm the plugin is active, the server registration points to the built metadata and the editor bundle loads without errors.

Source changes do nothing: rebuild, check the generated file changed and clear the relevant browser or page cache. Do not edit both source and generated copies independently.

The editor reports invalid content: compare the saved HTML with the current save function. A structural change to a static block needs a migration strategy, not repeated “recovery” clicks across production posts.

The style is missing: compare block.json's filename with the real build output. Its path is relative to the metadata file, not the original source directory.

The PHP-rendered notice is blank: check that the render file reached the build, the render property is present and the attributes are named consistently.

Deactivate the local sample to undo the experiment. Before retiring a real block, replace or export its content in a usable form, especially if it has no saved fallback. For a PHP-template workflow driven by fields instead of this native JavaScript editor, use the separate ACF Blocks tutorial. For a smaller text-based integration, the shortcode examples may be enough.