Dynamic PHP content in Block Theme template file

I would say that the proper process for this would be:

  1. Create a Dynamic Block according to the documentation.
    • The article doesn’t mention it, but you will need to use a tool like @wordpress/scripts to be able to write block JavaScript in the style shown in the documentation. The process for creating a block with this tool is described here.
    • Despite what the article says, I would not necessarily bother rendering the preview with client-side JavaScript. Instead just follow the example under the “Live rendering in the block editor” heading and use ServerSideRender to use your PHP to render the preview.
    • If you only intend to use this block in a template, set supports.inserter to false in block.json to hide it from the regular block inserter.
  2. In your theme’s HTML template, include your custom block with a block comment:
    <!-- namespace:block-name /-->. Dynamic blocks with no attributes don’t need anything more than this in a template. Think of this a bit like a shortcode.
  3. To prevent your block from being moved or removed from the template you can pass a lock attribute to the block. In a template that will look like this:
    <!-- namespace:block-name {"lock":{"move":false,"remove":false}} /-->. That last bit is JSON written on one line.

Just to address something else you said:

I understand that the above is to be expected. I have also seen it
recommended to use a dynamic block (…),
however, this sort of trips me up because it is a mix of JavaScript
(can’t tell at first glace if it’s intended to be run client-side or
server-side) and PHP. Of course, historically, most aspects of the
page would be generated dynamically, server-side on page request.

All JavaScript involved in WordPress development is client-side. WordPress does not use or require any server-side JavaScript. That would require a Node.js server and WordPress does not (and cannot) run on Node.

The JavaScript that you write for blocks is written for use in the block editor. All blocks are mini React applications and the JavaScript you write is to provide an interface for the block in the editor. Blocks require at least 2 scripts: An edit script, which provides the preview and editing interface; and a save script, which generates static HTML that is saved into the database.

When you create a dynamic block, you do not save any HTML to the database, because your block will instead use PHP to render its output. Instead only the block comment (shown above) is saved, and this is used as a placeholder for the PHP-generated content, which is shown on output.

tech