Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk11 min

How to Create PHP-Only Custom Gutenberg Blocks

A complete guide to building dynamic Gutenberg blocks without a JavaScript registration file, using PHP registration, render_callback, block.json, safe escaping, and practical troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can create a dynamic Gutenberg block without a JavaScript registration file by registering it in PHP with register_block_type(), setting supports.autoRegister to true, and returning front-end markup from a render_callback (or a PHP template declared in block.json). WordPress stores the block comment and attributes, then runs your PHP renderer whenever the post is displayed. This is a strong fit for server-driven notices, listings, account data, and other output that should always reflect current PHP-side data.

What a PHP-only Gutenberg block is

A PHP-only block is registered on the WordPress server during the init action. It has a block name, attributes, supports settings, and a server renderer, but no JavaScript file is required to register the block. The editor can insert the block because WordPress knows its registration data from PHP.

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.

The usual implementation is a dynamic block. Instead of saving the final HTML in post content, the block saves its delimiter comment and attribute values. When WordPress renders the post, it invokes your callback and uses the returned HTML. That means a changed option, template, query, or other server-side value can appear immediately without requiring every post to be edited and resaved.

WordPress Developer Resources describes this pattern for blocks that only need server-side rendering: register them exclusively in PHP with the autoRegister flag and a render_callback. The same registration API is used whether the callback is a named function, a closure, or a PHP template loaded through block metadata.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

When PHP-only is a good fit

  • Output is generated from PHP or data that changes on the server.
  • The block needs straightforward attributes such as text, IDs, filters, or display choices.
  • You want one rendering path for the editor preview and the front end.
  • You are maintaining an existing PHP template and do not need a large client-side editing interface.
  • You want to avoid a JavaScript build and registration bundle for a small, server-oriented block.

When to choose a JavaScript-assisted block instead

PHP-only registration is less suitable when the editor must provide rich, highly interactive controls, instant client-side manipulation, drag-and-drop behavior, or complex previews that change on every keystroke. Official guidance notes that client-side rendering is faster for editor manipulation, while server rendering is useful when established PHP rendering logic is central. You can still combine server registration with a client component later if the editing experience grows beyond what a PHP-only block can comfortably provide.

How the registration and rendering lifecycle works

  1. WordPress fires init while loading the site.
  2. Your plugin calls register_block_type() with a unique block name and configuration.
  3. The block editor receives the registered name, attributes, and supports. Because autoRegister is enabled, a separate JavaScript registration file is not required.
  4. When an editor inserts or updates the block, WordPress stores the block delimiter and attribute values. A dynamic block can have a null save result, so generated markup is not persisted in the post.
  5. When the post is rendered, WordPress passes the stored attributes to the callback. The callback returns the HTML that appears on the front end.

The registration function returns a WP_Block_Type object when registration succeeds and false when it fails. Checking that return value while developing can reveal a malformed name or invalid registration data before you start debugging the renderer.

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

Build a minimal PHP-only block plugin

1. Create the plugin file

Create a directory inside wp-content/plugins, for example my-php-notice, and add a PHP file with the same general name. A plugin header makes it visible on the Plugins screen.

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

Use a namespace that is unique to your project. A block name has the form namespace/block-name; in the example, my-plugin/notice identifies the block. Do not use a generic namespace that could collide with another plugin.

2. Register the block during init

Put registration in a function hooked to init. The complete minimal registration declares API version 3, one string attribute, automatic registration, color support, and a callback.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
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' );

api_version identifies the block API contract. The attributes array defines data stored with the block; here, message is a string with a default value. The supports array opts into automatic editor registration and declares that the block can receive background and text color settings. Those supports can contribute classes or styles to the wrapper when you use get_block_wrapper_attributes().

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

3. Add the server renderer

The callback receives the block attributes, the inner content string, and the block instance. A simple notice does not need inner content, but retaining the parameters keeps the callback compatible with WordPress’s dynamic-rendering signature.

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

The fallback protects the renderer if an older block instance has no message attribute. get_block_wrapper_attributes() produces the attributes WordPress needs for the block wrapper and lets registered supports, such as text and background color, participate. esc_html() treats the message as text, so a value entered by an author cannot become executable markup. Return the complete HTML string; do not echo it from the callback.

4. Activate and insert the block

  1. Save the plugin file in its plugin directory.
  2. Activate the plugin from the WordPress Plugins screen.
  3. Open the block editor and search for the block title or its namespace.
  4. Insert the block, change the message, and optionally apply the available color controls.
  5. Save or publish the post, then view the front end and confirm that the message and wrapper classes or styles are present.

If the block does not appear, first verify that the plugin is active and that the registration function is actually attached to init. A PHP parse error prevents the plugin from loading at all, so check the site’s PHP error log before investigating editor behavior.

Use block.json for a maintainable block

Inline registration is convenient for a very small block. A metadata directory is easier to maintain when the block has several attributes, supports, styles, or a PHP template. The render property points to a PHP file and was introduced in WordPress 6.1.

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.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Recommended file layout

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

Declare metadata in block.json

{
  "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 metadata describes the same contract as the inline array: the public block name, editor title, category, attribute schema, and supports. Keep the name identical to the name used by existing content; changing it creates a different block and can leave old posts pointing at an unregistered type.

Register the metadata directory

In the main plugin file, pass the directory containing block.json to register_block_type().

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

WordPress reads the metadata and associates the declared render template with the block. The call still belongs on init; registering too early can run before the block system is ready.

Render from render.php

The template receives $attributes, $content, and $block in the dynamic-rendering model. Keep the file focused on preparing and printing the block’s output.

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.
<?php
$message = isset( $attributes['message'] )
    ? $attributes['message']
    : 'Hello from PHP';

$wrapper_attributes = get_block_wrapper_attributes();
?>
<div <?php echo $wrapper_attributes; ?>>
    <?php echo esc_html( $message ); ?>
</div>

Escape each value for its context. Text belongs in esc_html(); an attribute value requires an attribute-specific escaping function, and a URL requires URL validation and escaping. Do not assume that an attribute is safe because it was declared in block.json: attributes can come from imported content, older posts, REST requests, or another plugin.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Dynamic rendering, saved content, and data freshness

A static block saves generated markup in post content. That can be simple for fixed output, but changing the rendering logic later may make the saved markup differ from what the editor expects, causing validation problems. A dynamic block avoids that stale-HTML problem by saving the block comment and attributes while generating the markup at render time.

For a PHP-only block, the save side can be null. WordPress then calls the server renderer whenever it needs the block’s output. If your callback reads a server-side value, updates to that value can appear in every post that uses the block without a content migration. The trade-off is that every render depends on the callback remaining available and returning valid HTML; removing or renaming the callback can leave the block unable to render.

Attributes are the persistent contract between the editor and the renderer. Give each attribute a clear type and default, handle missing keys defensively, and preserve compatibility when you add new attributes. A renderer should continue producing sensible output for content created before the latest version of the plugin.

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

Editor experience and live previews

Automatic registration supplies the block definition without a JavaScript registration file, but it does not turn PHP into a rich client-side editing system. The editor can expose the registered block and its supported controls; advanced custom interfaces still require client-side code.

If an existing PHP renderer must be used for a live editor preview, the @wordpress/server-side-render component requests the block’s renderer through /wp/v2/block-renderer/:block. The block and its attributes must already be registered in PHP. This approach keeps the authoritative markup in PHP while allowing a JavaScript editor component to refresh the preview when attributes change.

Use server-side previews selectively. A request on every change can make a complex block feel slower than a local preview, and the endpoint will only work when the server registration, permissions, and attributes are valid. For a simple PHP-only block, relying on the normal dynamic output may be sufficient.

PHP-only versus conventional server-and-client registration

Concern PHP-only auto-registered block Conventional server + client registration
JavaScript required for registration No Usually yes for editor settings and controls
Rendering Server-side callback or PHP template Static save output or a server-side callback, often paired with a client editor
Best fit Server-driven, low-interactivity output Rich editor controls and interactive previews
Data freshness Generated at render time Depends on whether the block is static or dynamic
Supports integration Available through server registration Available when the block is registered on the server

The choice is architectural rather than ideological. If PHP already owns the output and the editor only needs basic attributes, PHP-only registration minimizes moving parts. If authors need a sophisticated editing canvas, use a client registration layer while retaining a server callback where current server data or shared PHP templates matter.

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

Security and output-quality checklist

  • Use a unique namespace and block name to avoid collisions.
  • Escape every user-controlled value at the point where it is printed.
  • Use get_block_wrapper_attributes() so declared supports are reflected in the wrapper.
  • Return markup from the callback instead of echoing fragments unpredictably.
  • Provide defaults for missing attributes and test content created with older versions.
  • Keep template logic small; move substantial data preparation into a function that can be tested separately.
  • Do not trust values merely because they came from the editor or a metadata schema.
  • Check the HTML returned by the callback for balanced tags and valid nesting.

Troubleshooting common failures

Symptom Likely cause Fix
The block is missing from the inserter The plugin is inactive, registration never ran, or the PHP file has a fatal error. Activate the plugin, confirm the init hook, and inspect the PHP error log.
Existing posts show an unknown block The namespace or block name changed. Restore the original name or provide a deliberate migration path; names are part of stored content.
The editor reports invalid content A block intended to be dynamic is saving markup, or the saved structure no longer matches the registered definition. Use a dynamic save result of null for server-rendered output and keep the attribute schema compatible.
Attributes are empty in the callback The key is missing, the type is wrong, or the metadata and PHP registration disagree. Compare the attribute name, type, and default in one registration source, then add a defensive fallback.
Color controls have no visible effect The renderer does not output the wrapper attributes. Call get_block_wrapper_attributes() and place its result on the block’s outer element.
Markup appears as text or breaks the page HTML was escaped in the wrong context or tags are unbalanced. Escape text values, keep intentional markup separate, and inspect the exact returned string.
A metadata block does not render The directory path is wrong, block.json is invalid, or the WordPress version does not support the declared render property. Point registration at the directory containing the metadata file, validate the JSON, and account for the render property being introduced in WordPress 6.1.
A server-side editor preview fails The block is not registered in PHP or the renderer endpoint receives invalid attributes. Confirm PHP registration first, then inspect the request to /wp/v2/block-renderer/:block and the attributes sent to it.

A practical decision process

  1. Identify the source of truth. If PHP data or an existing PHP template determines the output, dynamic server rendering is a natural starting point.
  2. List the editor’s required controls. Text fields and a few supported styles can stay PHP-only; highly interactive controls point toward a client editor.
  3. Choose registration format. Use inline PHP for a tiny block, or block.json plus render.php when metadata and template files will grow.
  4. Define a stable attribute contract. Set types and defaults, and decide how missing or legacy values should render.
  5. Implement and escape the renderer. Build the wrapper with get_block_wrapper_attributes(), escape dynamic values, and return the HTML.
  6. Test both contexts. Insert and edit the block in the editor, then view a published post and test an older instance with missing attributes.
  7. Document the name and migration plan. The namespace and block name are stored in content; changing them later is not a cosmetic rename.

What this pattern can and cannot replace

PHP-only registration replaces the JavaScript needed to register a basic block and centralizes rendering on the server. It does not eliminate the need for careful attribute design, escaping, testing, or editor decisions. Nor does it automatically provide a custom inspector panel, a complex visual canvas, or client-side state management. Those requirements determine whether you later add a JavaScript editor while keeping the same server renderer.

For a notice, server-fed card, account-specific message, or other low-interactivity component, the pattern is deliberately small: register on init, declare attributes and supports, render with a callback or template, and let WordPress generate current markup when the post is displayed. That gives the block a stable place in post content without freezing its HTML at the moment an editor clicks Save.

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 *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.