Build a Custom Gutenberg Block with Dynamic Server-Side Rendering in WordPress

Build a custom Gutenberg block with dynamic server-side rendering

A custom block gives full control over the editor experience and the front-end output, without shortcodes. There are two kinds. A static block saves its HTML into the post content with a save function. A dynamic block saves only its attributes, and PHP builds the HTML on every page view. Dynamic is the right choice when the output depends on data that changes (recent posts, prices, availability) or when you want to change the markup later without “block validation” errors in old posts.

Problem: A repeated content element (a callout box) is done with a shortcode: no preview in the editor, no settings panel, and the markup is stuck in the posts.

Solution: Scaffold a dynamic block with @wordpress/create-block, describe its attributes in block.json, build the editor UI with RichText and InspectorControls, and render the front end in render.php.

Scaffold

npx @wordpress/create-block my-callout-block --variant=dynamic
cd my-callout-block
npm start   # watch mode during development

This creates a plugin with block.json, src/edit.js, src/render.php and the build setup. npm run build makes the production bundle in build/, which the plugin loads.

block.json

{
    "$schema": "https://schemas.wp.org/trunk/block.json",
    "apiVersion": 3,
    "name": "myplugin/callout",
    "title": "Callout",
    "category": "text",
    "icon": "megaphone",
    "attributes": {
        "message": { "type": "string", "default": "" },
        "variant": { "type": "string", "enum": [ "info", "warning", "success" ], "default": "info" },
        "isDismissable": { "type": "boolean", "default": false }
    },
    "supports": { "html": false },
    "textdomain": "my-callout-block",
    "editorScript": "file:./index.js",
    "style": "file:./style-index.css",
    "render": "file:./render.php"
}

The attributes have no source, so they are stored in the block comment in the post content. "render" (WordPress 6.1+) points to the PHP template; apiVersion 3 is the current version since WordPress 6.3.

The editor: edit.js

import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, RichText } from '@wordpress/block-editor';
import { PanelBody, SelectControl, ToggleControl } from '@wordpress/components';

export default function Edit( { attributes, setAttributes } ) {
    const { message, variant, isDismissable } = attributes;
    const blockProps = useBlockProps( { className: `callout callout--${ variant }` } );

    return (
        <>
            <InspectorControls>
                <PanelBody title={ __( 'Callout settings', 'my-callout-block' ) }>
                    <SelectControl
                        label={ __( 'Type', 'my-callout-block' ) }
                        value={ variant }
                        options={ [
                            { label: 'Info', value: 'info' },
                            { label: 'Warning', value: 'warning' },
                            { label: 'Success', value: 'success' },
                        ] }
                        onChange={ ( value ) => setAttributes( { variant: value } ) }
                    />
                    <ToggleControl
                        label={ __( 'Dismissable', 'my-callout-block' ) }
                        checked={ isDismissable }
                        onChange={ ( value ) => setAttributes( { isDismissable: value } ) }
                    />
                </PanelBody>
            </InspectorControls>
            <div { ...blockProps }>
                <RichText
                    tagName="p"
                    value={ message }
                    onChange={ ( value ) => setAttributes( { message: value } ) }
                    placeholder={ __( 'Enter callout message…', 'my-callout-block' ) }
                />
            </div>
        </>
    );
}

A dynamic block has no save function (or save returns null): nothing but the attributes goes into the post.

The front end: render.php

<?php
// $attributes, $content and $block are available here
$variant = in_array( $attributes['variant'], array( 'info', 'warning', 'success' ), true ) ? $attributes['variant'] : 'info';
?>
<div <?php echo get_block_wrapper_attributes( array( 'class' => 'callout callout--' . $variant ) ); ?>>
    <p class="callout__message"><?php echo wp_kses_post( $attributes['message'] ); ?></p>
    <?php if ( $attributes['isDismissable'] ) : ?>
        <button type="button" class="callout__close" aria-label="<?php esc_attr_e( 'Dismiss', 'my-callout-block' ); ?>">&times;</button>
    <?php endif; ?>
</div>

RichText stores inline HTML (bold, links), so the message is printed with wp_kses_post(), not esc_html(). Attributes come from the post content and can be edited by anyone who can edit the post, so check them like any other input.

NOTE: A dynamic block that lists content usually queries a custom post type with WP_Query in render.php, see registering a custom post type. In the editor, ServerSideRender from @wordpress/server-side-render can show the same PHP output as the preview, so you do not have to rebuild the markup in React.