Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 68 ยท REST API, AJAX and Blocks

Dynamic Blocks and Block Bindings

Learn dynamic blocks in WordPress - render.php and render_callback, get_block_wrapper_attributes, the Interactivity API overview, the Block Bindings API and when to go dynamic.

A static block stores its final HTML in the database, as you saw in the block overview. That is perfect for a paragraph, but wrong for a "latest posts" list or a "current price" label: the content would be frozen at the moment someone clicked Update. A dynamic block stores only its attributes and lets PHP build the HTML each time the page is rendered.

This lesson shows how a dynamic block is wired up, what PHP receives, how to print the wrapper correctly, and how to decide whether a block should be dynamic. It also gives a short tour of two newer features: the Interactivity API for front-end behavior, and the Block Bindings API, which fills a block's attributes from a data source such as post meta.

WordPress cannot run on this site. The real block code is read-only. The runnable examples are plain-PHP stand-ins: one renders a block from its attributes, the other resolves bindings. They imitate the idea and are not WordPress's own functions.

What changes in a dynamic block

Three things differ from a static block:

  1. save returns null (or you leave it out), because nothing is stored besides the comment.
  2. The stored content is a self-closing comment such as <!-- wp:myplugin/latest-books {"count":3} /-->.
  3. PHP supplies the front-end HTML.
flowchart LR
    A["Post content:<br/>wp:myplugin/latest-books {count: 3}"] --> B["parse_blocks()"]
    B --> C["render_block()"]
    C --> D["render.php or render_callback"]
    D --> E["Fresh HTML for this request"]

A dynamic block keeps attributes in the database and builds its HTML at render time.

Because the HTML is rebuilt on every request, changing the PHP changes every existing post at once, and you never need a deprecation for markup changes. The price is a bit of server work per view, which caching (see caching and WP-Cron) takes care of on busy sites.

render.php: the modern way

Add one key to block.json:

JSON
{
  "apiVersion": 3,
  "name": "myplugin/latest-books",
  "title": "Latest Books",
  "category": "widgets",
  "attributes": {
    "count": { "type": "integer", "default": 3 }
  },
  "supports": { "html": false, "align": true },
  "editorScript": "file:./index.js",
  "render": "file:./render.php"
}

Then create render.php next to the built block.json. WordPress includes the file whenever the block renders, and three variables are available in it: $attributes (the saved attributes, with defaults filled in), $content (the block's inner HTML, used by blocks with InnerBlocks), and $block (the WP_Block object, with $block->context for inherited data such as the current post ID).

PHP
<?php
// build/render.php (real WordPress, read-only)
$books = get_posts( [
    'post_type'      => 'book',
    'posts_per_page' => (int) $attributes['count'],
    'no_found_rows'  => true,
] );

if ( ! $books ) {
    return;
}
?>
<ul <?php echo get_block_wrapper_attributes(); ?>>
    <?php foreach ( $books as $book ) : ?>
        <li><a href="<?php echo esc_url( get_permalink( $book ) ); ?>">
            <?php echo esc_html( get_the_title( $book ) ); ?>
        </a></li>
    <?php endforeach; ?>
</ul>

Notice get_posts() from the WP_Query lesson with no_found_rows, and that every printed value goes through an escaping function: see escaping output.

The older style is a callback passed to register_block_type(). It works for blocks that are not built from a block.json folder, or when you prefer a function:

PHP
<?php
register_block_type( __DIR__ . '/build', [
    'render_callback' => function ( array $attributes, string $content, WP_Block $block ): string {
        return '<p>' . esc_html( $attributes['label'] ?? '' ) . '</p>';
    },
] );

A callback must return the HTML string, while render.php can either print it or return it.

get_block_wrapper_attributes

In the editor, useBlockProps() adds the wrapper's classes, styles and attributes. On the PHP side, get_block_wrapper_attributes() does the same job. It prints the generated class wp-block-myplugin-latest-books, any className the editor typed in, and everything produced by supports such as color, spacing and alignment. You can add your own values:

PHP
<?php
echo get_block_wrapper_attributes( [ 'class' => 'is-compact', 'data-count' => (string) $attributes['count'] ] );

If you skip it, a block loses its support-driven styles, so treat it as required on the outermost element. The function returns an already escaped string of attributes, ready to echo inside a tag.

Live preview in the editor

A dynamic block still needs an edit component, because the editor runs in JavaScript. The simplest option is the ServerSideRender component from @wordpress/server-side-render, which asks the server for the block's HTML and shows it as a preview:

JSX
// edit.js (read-only)
import ServerSideRender from '@wordpress/server-side-render';
import { useBlockProps } from '@wordpress/block-editor';

export default function Edit( { attributes } ) {
    return (
        <div { ...useBlockProps() }>
            <ServerSideRender block="myplugin/latest-books" attributes={ attributes } />
        </div>
    );
}

It is easy, but each attribute change causes a request. For blocks with heavy controls, many developers write a real JavaScript preview and keep PHP for the front end.

Try it: a server-render stand-in

This stand-in keeps a registry of block names and render callbacks, fills defaults, builds a wrapper attribute string, and escapes everything it prints. It shows why the same stored comment can produce different HTML as the data changes.

PHP Rendering dynamic blocks from attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second call stores no count at all: the default of 3 comes from the schema, the same way block.json defaults work. And the <b> in the name arrives as text, because output is escaped at the moment it is printed.

The Interactivity API in one page

Static front-end behavior (a toggle, a counter, a live filter) used to mean writing custom JavaScript and wiring it by hand. WordPress now ships the Interactivity API, a small reactive layer for dynamic blocks. You mark up the HTML in render.php with data-wp-* directives and describe state and actions in a module script:

PHP
<?php
// render.php (read-only)
$context = [ 'open' => false ];
?>
<div <?php echo get_block_wrapper_attributes(); ?>
     data-wp-interactive="myplugin/details"
     <?php echo wp_interactivity_data_wp_context( $context ); ?>>
    <button data-wp-on--click="actions.toggle" data-wp-bind--aria-expanded="context.open">
        Details
    </button>
    <div data-wp-bind--hidden="!context.open">Hidden content.</div>
</div>
JavaScript
// view.js (read-only), loaded with "viewScriptModule" in block.json
import { store, getContext } from '@wordpress/interactivity';

store( 'myplugin/details', {
    actions: {
        toggle() {
            const context = getContext();
            context.open = ! context.open;
        },
    },
} );

The server renders the initial HTML, and the module takes over in the browser. Use it when a block needs behavior after load; for plain output, PHP alone is enough.

Block Bindings: attributes from a data source

Block bindings let a core block pull an attribute from somewhere else. The binding lives in the block's comment under metadata.bindings:

HTML
<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"core/post-meta","args":{"key":"book_author"}}}}} -->
<p>Fallback text</p>
<!-- /wp:paragraph -->

When this block renders, WordPress asks the source core/post-meta for the value of book_author on the current post and puts it into the paragraph's content. The editor can use the same data. Core ships a few sources (post meta is the main one; the meta key must be registered for the editor to expose it), and only some attributes of some core blocks can be bound, such as paragraph and heading content, image url and alt, and button text and url.

You can add your own source in PHP:

PHP
<?php
add_action( 'init', function (): void {
    register_block_bindings_source( 'myplugin/price', [
        'label'              => __( 'Book price', 'myplugin' ),
        'get_value_callback' => function ( array $source_args, WP_Block $block_instance, string $attribute_name ) {
            $post_id = $block_instance->context['postId'] ?? 0;
            $cents   = (int) get_post_meta( $post_id, 'book_price_cents', true );
            return '$' . number_format( $cents / 100, 2 );
        },
        'uses_context'       => [ 'postId' ],
    ] );
} );

This builds on custom fields and post meta, and it is a neat way to show meta values in a template without a dynamic block or a shortcode.

Try it: resolving bindings

This stand-in walks a list of blocks, finds metadata.bindings, asks the registered source for each value and replaces the attribute. A missing value keeps the fallback, which matches the idea that a binding should degrade gracefully.

PHP A block bindings resolver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Post 13 has an author but no price, so the price paragraph falls back to its own text.

When should a block be dynamic?

Go dynamic when the output depends on data that changes (posts, prices, the current user, the date), when you want to change the markup later without migrating old posts, or when you need server-only logic. Stay static when the output is fixed content typed by the editor, because static blocks are cheaper to serve and work without PHP running the block. Many real blocks mix both: a static container with dynamic children, or a static wrapper around a bound value.

Common mistakes

  • Not escaping in render.php. Attributes are user input. Use esc_html(), esc_attr() and esc_url().
  • Forgetting the wrapper function. Without get_block_wrapper_attributes(), supports like color and spacing do nothing on the front end.
  • Printing instead of returning in a callback. A render_callback must return a string.
  • Heavy queries on every view. Add no_found_rows, limit counts and cache results when needed.
  • Binding unsupported attributes. Only some core block attributes can be bound.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is stored in post_content for a dynamic block?

    PHP builds the HTML at render time, so the database keeps just the comment and its attribute JSON.
  2. 2. Which variables does render.php receive?

    WordPress provides the saved attributes, the inner block HTML, and the WP_Block instance with its context.
  3. 3. Why should the outermost element use get_block_wrapper_attributes()?

    It is the PHP counterpart of useBlockProps and carries the wrapper classes, custom class names and support-generated styles.
  4. 4. What does a block binding with source core/post-meta do?

    The binding asks the source for a value, here a meta key of the current post, and substitutes it for the attribute.
  5. 5. Which content is best kept as a static block?

    Fixed editor-written content does not depend on changing data, so static output is simpler and cheaper.

Summary

  • Dynamic blocks store attributes only and build HTML in PHP, via render.php (from block.json) or a render_callback.
  • In render.php you get $attributes, $content and $block; a callback returns the string.
  • Use get_block_wrapper_attributes() on the outer element and escape every printed value.
  • ServerSideRender previews a dynamic block in the editor; the Interactivity API adds front-end behavior with data-wp-* directives.
  • Block bindings fill supported attributes from sources such as core/post-meta or your own register_block_bindings_source().
  • Go dynamic for changing data; stay static for fixed content.
  • The runnable examples are plain-PHP stand-ins, not WordPress code.

Next: Forms and Nonces