DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
VGSources
Blog

How to Create PHP-Only Custom Gutenberg Blocks

A complete WordPress developer guide to building Gutenberg blocks with PHP only, including server registration, dynamic callbacks, block.json templates, escaping, editor limits, and troubleshooting.
Length11 min Posted Quest giverVGSources Team

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes—you can create a custom Gutenberg block without a JavaScript registration file. Register the block during WordPress’s init hook with register_block_type(), set supports.autoRegister to true, and provide a PHP render_callback (or a PHP template declared in block.json). WordPress stores the block name and attributes in post content, then generates the front-end HTML on the server whenever the post is rendered.

This approach is ideal for server-driven output such as notices, account data, query results, or markup that already exists in PHP. It is less suitable for blocks that need sophisticated live editing, drag-and-drop behavior, or a highly interactive preview in the editor.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What a PHP-only Gutenberg block does

A conventional custom block often uses JavaScript to register its name, editor interface, attributes, and save behavior. A PHP-only block moves registration and rendering to the server. The editor can discover the block from the server registration, while PHP controls the markup that appears on the front end.

The essential registration has three parts:

  • A unique block name such as my-plugin/notice.
  • supports => array( 'autoRegister' => true ), which allows the block to be registered for editor use without a JavaScript registration file.
  • A render_callback that returns the block’s HTML.

WordPress calls the registration code on init. When a post contains the block, WordPress passes its attributes to the callback and uses the returned string as the rendered output.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

When this pattern is the right choice

Good fits

  • Output depends on current server data, such as a user’s account status or a database query.
  • You already have a PHP rendering function or template that should remain the single source of truth.
  • The editor only needs basic block insertion and attribute editing.
  • You want to avoid maintaining a build pipeline and a separate JavaScript bundle for a small block.
  • The front-end markup may change independently of old post content.

Situations that call for JavaScript

  • The block needs rich controls, custom inspector panels, immediate previews, or complex interactions while editing.
  • Editors must manipulate nested data visually or see client-side calculations before saving.
  • The block relies on browser APIs or interaction that cannot be represented by server-rendered HTML.

Server rendering keeps PHP logic central, but client-side rendering is generally faster for manipulating a complex editor interface. Choose the smallest architecture that gives editors the controls they actually need.

Prerequisites and file layout

You need a WordPress plugin (or theme code), PHP access, and a WordPress installation that supports the block APIs used by your example. The examples below use block API version 3. The metadata approach’s render property was introduced in WordPress 6.1.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A minimal plugin can be a single file:

<?php
/**
 * Plugin Name: PHP Only Notice Block
 */

For a metadata-based block, use a directory such as:

my-plugin/
├── my-plugin.php
└── notice/
    ├── block.json
    └── render.php

Keep the block namespace specific to your plugin or project. Names are global within the editor, so a generic name can collide with another plugin.

Build a PHP-only block with register_block_type()

1. Register the block on init

Create a plugin file and register the block from an init callback. The registration function returns a WP_Block_Type object when registration succeeds and false if it fails, so a return value can be checked while debugging.

<?php
/**
 * Plugin Name: PHP Only Notice Block
 */

function my_plugin_register_notice_block() {
    register_block_type(
        'my-plugin/notice',
        array(
            'api_version' => 3,
            'attributes' => array(
                'message' => array(
                    'type'    => 'string',
                    'default' => 'Hello from PHP',
                ),
            ),
            'supports' => array(
                'autoRegister' => true,
                'color' => array(
                    'background' => true,
                    'text' => true,
                ),
            ),
            'render_callback' => 'my_plugin_render_notice_block',
        )
    );
}
add_action( 'init', 'my_plugin_register_notice_block' );

The first argument is the permanent block name. Use a lowercase namespace and name separated by one slash. The attributes declaration tells WordPress what data can be stored with the block. Here, message is a string with a default value, so a newly inserted block can render useful output even before an editor changes it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

The supports declaration enables editor capabilities that WordPress knows how to apply to the block. In this example, the color support allows background and text color settings. Those settings are not automatically printed by arbitrary markup; the wrapper helper described below adds the generated attributes to the outer element.

2. Add the server render callback

The callback receives the block attributes, the saved inner content, and the current block instance. Return the final HTML string; do not print it directly.

function my_plugin_render_notice_block( $attributes, $content = '', $block = null ) {
    $message = isset( $attributes['message'] )
        ? $attributes['message']
        : 'Hello from PHP';

    $wrapper_attributes = get_block_wrapper_attributes();

    return sprintf(
        '<div %1$s>%2$s</div>',
        $wrapper_attributes,
        esc_html( $message )
    );
}

get_block_wrapper_attributes() produces the standard wrapper attributes for the block. When color support is enabled, the helper can include the classes and inline style values needed for the selected colors. It also helps the block follow WordPress’s expected wrapper conventions and makes theme styling more predictable.

The message is escaped with esc_html() because it is user-controlled block data. Escape for the context in which a value is printed: use HTML escaping for text nodes, attribute escaping for attribute values, and URL escaping for links. Never treat an attribute as trusted simply because it came from the editor.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Activate and insert the block

  1. Put the PHP file in a plugin directory inside wp-content/plugins.
  2. Activate the plugin from Plugins in the WordPress admin.
  3. Open the block editor and select the block inserter.
  4. Search for the block title or name exposed by the registration.
  5. Insert the block, change its message or color settings, save the post, and view the front end.

If the block does not appear, first confirm that the plugin is active and that the registration function is attached to init. A PHP parse error or a registration failure can prevent the block from being available at all.

Use block.json for metadata and a PHP template

A metadata file is useful when the block has several attributes, supports, styles, or a dedicated rendering template. It keeps descriptive information in a standard format and prevents a large registration array from becoming difficult to maintain.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

The metadata file

{
  "apiVersion": 3,
  "name": "my-plugin/notice",
  "title": "PHP Notice",
  "category": "widgets",
  "attributes": {
    "message": {
      "type": "string",
      "default": "Hello from PHP"
    }
  },
  "supports": {
    "autoRegister": true,
    "color": {
      "background": true,
      "text": true
    }
  },
  "render": "file:./render.php"
}

The render property points to the PHP file that generates the block output. The file: prefix makes the path relative to block.json. This property is available from WordPress 6.1 onward.

Register the metadata directory

Point register_block_type() at the directory containing block.json:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
add_action( 'init', function () {
    register_block_type( __DIR__ . '/notice' );
} );

WordPress reads the metadata, registers the attributes and supports, and connects the render template. The directory path must be correct on the server; a typo here commonly results in a block that never registers.

Render the block in render.php

<?php
$message = isset( $attributes['message'] )
    ? $attributes['message']
    : 'Hello from PHP';

$wrapper_attributes = get_block_wrapper_attributes();

printf(
    '<div %1$s>%2$s</div>',
    $wrapper_attributes,
    esc_html( $message )
);

For metadata-based dynamic rendering, WordPress makes $attributes, $content, and $block available to the template. The template should focus on output. Keep registration, data preparation, and reusable business logic in separate functions when the block grows.

How dynamic rendering and saved content work

A dynamic block generates its front-end markup when WordPress renders the post. The post content stores the block delimiter comment and its serialized attributes rather than relying on a permanent copy of generated HTML. If the render callback returns different markup later, the front end reflects the new logic without requiring every post to be opened and resaved.

For a dynamic block, the save result can be null. In the PHP-only pattern there is no JavaScript save function to maintain a second copy of the markup; PHP is the renderer. The stored attributes remain the persistence layer, while the callback is the presentation layer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Why this prevents stale output

  • Current database values can be queried each time the page is viewed.
  • Template changes apply to existing posts immediately after caches are refreshed.
  • Conditional output can respond to the current user, date, or site configuration.

Dynamic rendering also means front-end output depends on PHP execution. A fatal error, missing function, or malformed return value can affect every post containing the block, so test changes on staging and keep the callback small and defensive.

PHP-only versus JavaScript-assisted blocks

Axis PHP-only auto-registered block Conventional server and client registration
JavaScript required for registration No registration file is required. Usually yes for editor settings and controls.
Rendering Server-side callback or PHP template. Static saved markup, server-side rendering, or a combination.
Best fit Server-driven, low-interactivity output. Rich editor controls and interactive previews.
Data freshness Generated at render time. Depends on whether the design is static or dynamic.
Supports integration Available through server registration. Available when the block is also registered on the server.

A static block saves generated markup in post content. That can be simpler for fixed output, but changing the save markup later can cause validation warnings because the saved HTML no longer matches what the editor expects. Dynamic rendering avoids that class of stale-markup problem, at the cost of rendering on the server for every request that is not served from cache.

Editor previews and server-side rendering requests

A PHP-only block can be inserted and configured without a JavaScript registration file, but its editor experience is intentionally limited. If an existing PHP renderer needs to provide a live preview inside a richer client-side interface, the @wordpress/server-side-render package can request the server output through the REST route /wp/v2/block-renderer/:block.

For that request to work, the block and its attributes must already be registered in PHP. The endpoint does not replace registration; it invokes the registered renderer with the requested attributes. Use this approach when the preview must match established PHP output, and avoid it for controls that could be rendered immediately in the browser.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Attribute design and validation

Choose types that match stored data

Declare strings, numbers, booleans, arrays, and objects according to the values the block actually stores. A string attribute should not be treated as an array merely because a malformed request supplied one. Check presence and type before using values in queries or output.

Provide safe defaults

Defaults keep older content and newly inserted blocks renderable. The callback should still handle missing attributes because posts can outlive a plugin version, migrations can be incomplete, and users can paste malformed block markup.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Keep stored data small

Store identifiers and choices rather than duplicating large generated documents. For example, store a post ID and query the current title at render time instead of persisting a title that may become obsolete.

Security and output correctness

  • Escape plain text with esc_html().
  • Escape values printed inside attributes with esc_attr().
  • Use esc_url() for URLs and restrict protocols where appropriate.
  • Do not pass arbitrary attribute values directly into SQL; use WordPress’s prepared-query APIs and validate IDs, dates, and enumerated choices.
  • Only allow limited HTML when the design requires formatted content, and sanitize it with an appropriate WordPress allow-list rather than printing raw input.
  • Return a complete, balanced HTML fragment. An unclosed element in a dynamic callback can disrupt the surrounding post layout.

Use the wrapper helper for the outer element, then keep the callback’s own markup explicit. This makes color supports, spacing classes, and theme expectations easier to maintain.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting checklist

The block is missing from the inserter

  • Confirm the plugin is activated and the PHP file has no syntax error.
  • Check that registration runs on init, not only when a particular admin screen loads.
  • Verify the block name has exactly one namespace slash and is unique on the site.
  • For metadata registration, confirm the directory path points to the folder containing block.json.
  • Check that the JSON is valid and that name, title, and apiVersion are present.

The block inserts but shows no output

  • Make sure render_callback names an existing callable function.
  • Ensure the callback returns a string instead of printing output or returning null accidentally.
  • Check PHP error logs for a fatal error in the callback or template.
  • Confirm that the callback reads the actual attribute key, including its capitalization.

Color settings do nothing

  • Verify that the relevant color supports are enabled in the registration or metadata.
  • Use get_block_wrapper_attributes() on the element that should receive WordPress’s generated classes and styles.
  • Inspect the front-end element to see whether the classes or style attribute are present; if they are present but invisible, the issue is likely theme CSS.

Changes are not visible

  • Clear page, object, and reverse-proxy caches after changing the renderer.
  • Check whether a persistent cache is serving an old copy of the post.
  • Confirm that the edited post contains the expected block name and serialized attribute values.
  • If the editor reports validation problems, determine whether the block was previously static and is now dynamic; old saved markup may require a deliberate migration strategy.

Testing a PHP-only block before release

  1. Activate the plugin on a staging site and insert a new block with default attributes.
  2. Change every supported attribute, including empty, boundary, and unexpected values.
  3. Save, reload the editor, and confirm the attributes persist.
  4. View the post while logged out and logged in to verify that conditional output behaves as intended.
  5. Check the generated HTML for escaped text, balanced tags, expected wrapper classes, and valid links.
  6. Edit the render callback, clear relevant caches, and verify that existing posts show the new output without being resaved.
  7. Deactivate the plugin and confirm that the failure mode is understood before deployment; missing registrations should not be allowed to produce silent data loss.

A practical decision framework

Choose a PHP-only block when the important requirement is dependable server output and the editor can work with basic attributes. Start with the direct registration example for one small block. Move to block.json when metadata, supports, styles, or a PHP template deserve their own files.

Choose a JavaScript-assisted block when editing itself is the product: complex controls, instant previews, nested interactions, or client-side behavior that cannot wait for a server request. You can still keep the final front-end renderer in PHP; the choice is about the editor experience, not only the output format.

Complete minimal example

The following single-file plugin is enough to demonstrate the complete PHP-only pattern:

<?php
/**
 * Plugin Name: PHP Only Notice Block
 */

function my_plugin_register_notice_block() {
    register_block_type(
        'my-plugin/notice',
        array(
            'api_version' => 3,
            'attributes' => array(
                'message' => array(
                    'type'    => 'string',
                    'default' => 'Hello from PHP',
                ),
            ),
            'supports' => array(
                'autoRegister' => true,
                'color' => array(
                    'background' => true,
                    'text' => true,
                ),
            ),
            'render_callback' => 'my_plugin_render_notice_block',
        )
    );
}
add_action( 'init', 'my_plugin_register_notice_block' );

function my_plugin_render_notice_block( $attributes, $content = '', $block = null ) {
    $message = isset( $attributes['message'] )
        ? $attributes['message']
        : 'Hello from PHP';

    $wrapper_attributes = get_block_wrapper_attributes();

    return sprintf(
        '<div %1$s>%2$s</div>',
        $wrapper_attributes,
        esc_html( $message )
    );
}

That pattern registers the block on the server, exposes it to the editor through autoRegister, stores a typed attribute, incorporates supported wrapper settings, and escapes the value before returning HTML. From there, add only the controls and data your block genuinely needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.