How to Build Dynamic Blocks for WordPress
Dynamic blocks in WordPress let you create content that updates automatically based on data, settings, or user input—without needing to edit the page each time. This guide walks you through building your first dynamic block from scratch, covering the PHP server-side rendering, block registration, and the JavaScript editor interface. You’ll need a WordPress site (version 5.0+), a code editor, and basic familiarity with PHP and JavaScript.
What You’ll Need
- A WordPress development environment (local or staging)
- A code editor (VS Code, Sublime Text, etc.)
- Basic knowledge of PHP and JavaScript (ES6+)
- Node.js and npm installed on your computer (for building the block)
- WordPress 5.0 or later (Gutenberg block editor)
Step-by-Step
- Set up the plugin folder. Create a new folder in
wp-content/plugins/for your plugin, e.g.,my-dynamic-block. Inside it, create a main PHP file namedmy-dynamic-block.phpwith the plugin header comment. - Initialize the plugin. Add the plugin header and a basic activation hook. The header should include the plugin name, description, and version. For example:
/* Plugin Name: My Dynamic Block */. - Create the block registration file. Inside the plugin folder, create a
src/directory for your JavaScript source. You’ll also need abuild/directory for compiled assets (we’ll set that up later). - Write the block’s JavaScript (editor side). In
src/index.js, import the necessary WordPress packages:registerBlockTypefrom@wordpress/blocks, anduseBlockPropsfrom@wordpress/block-editor. Define the block’s attributes (e.g., acontentstring) and theeditfunction that returns aRichTextcomponent for editing. - Define the block’s save function. For dynamic blocks, the
savefunction should returnnullbecause the server renders the output. This tells WordPress to use the server-side render callback. - Register the block server-side. In your main PHP file, use
register_block_typeto register the block. You’ll need to specify the block name (e.g.,my-plugin/dynamic-block), the editor script (the built JS file), and arender_callbackfunction that outputs the HTML. - Write the server-side render callback. This PHP function receives the block attributes and returns the HTML string. For example, if your block displays a message, the callback might wrap the attribute in a
<div>with a class. Usewp_kses_postto sanitize any user input. - Set up the build process. Create a
package.jsonfile in the plugin root with the necessary dependencies:@wordpress/scripts,@wordpress/blocks,@wordpress/block-editor, and@wordpress/i18n(for translations). Then runnpm install. - Add build scripts. In
package.json, add ascriptssection with"build": "wp-scripts build"and"start": "wp-scripts start". These use the WordPress scripts package to compile your JS. - Build the block. Run
npm run buildin the plugin folder. This generates the compiled JavaScript in thebuild/directory. Make sure the file name matches what you referenced inregister_block_type(e.g.,index.js). - Enqueue the editor script. In your PHP file, use
wp_register_scriptto register the built script with a handle, then pass it toregister_block_typeas theeditor_scriptargument. Also, you can enqueue a style for the front end if needed. - Test in the editor. Activate the plugin in WordPress. Create a new post, search for your block in the block inserter, and add it. You should see the editor interface you defined. Save the post.
- Test on the front end. View the published post. The block should display the server-rendered HTML. Change the block’s content and reload to confirm it updates.
- Add dynamic data (optional). To make the block truly dynamic, you can fetch data from the database or an external API in the render callback. For example, use
WP_Queryto list recent posts or callget_optionfor site settings.
Common Mistakes
- Forgetting to return
nullin thesavefunction—this causes the block to save static HTML and ignore the server render. - Not enqueueing the editor script correctly, leading to a block that doesn’t appear or errors in the editor.
- Using unescaped output in the render callback—always sanitize with
esc_htmlorwp_kses_postto prevent XSS. - Building the JS but not updating the file path in
register_block_type—the block may work in development but fail in production. - Overcomplicating the build process; stick to the official
@wordpress/scriptspackage to avoid configuration headaches.
Tips
- Use
useBlockPropsin your edit function to apply the block’s class name and other wrapper attributes automatically. - Leverage block variations to provide preset configurations for users.
- For complex dynamic data, consider using
wp_localize_scriptto pass data from PHP to the editor. - Test your block with the WordPress coding standards (PHPCS) to ensure compatibility and security.
- Keep your render callback pure: it should only take attributes and return HTML, not perform side effects.
Troubleshooting
- Block doesn’t appear in the editor: Check the browser console for JS errors. Ensure the editor script is enqueued and the block name is correct. Also, verify that the build succeeded and the file exists.
- Block renders as empty on the front end: Check the render callback—make sure it returns a string. Also, confirm that the block’s
savefunction returnsnull. - Changes in the editor don’t reflect on the front end: This can happen if you’re caching the page. Clear any caching plugins or server cache. Also, ensure the block’s attributes are correctly saved (check the post content in the database).
- PHP errors in the render callback: Enable WP_DEBUG in wp-config.php to see the errors. Common issues include undefined variables or calling functions that don’t exist.
- Build fails: Ensure Node.js and npm are up to date. Delete
node_modulesandpackage-lock.json, then runnpm installagain.
Frequently Asked Questions
What is the difference between a static and a dynamic block?
A static block saves its HTML content directly in the post content. A dynamic block saves only its attributes and renders the HTML on the fly via PHP. Dynamic blocks are ideal for content that changes frequently or depends on external data.
Do I need to use JavaScript for dynamic blocks?
Yes, you need JavaScript to define the block’s editor interface (how it appears and is edited in the Gutenberg editor). However, the front-end rendering is done entirely in PHP.
Can I use dynamic blocks without a build step?
Yes, you can write the editor script in plain JavaScript and enqueue it directly, but using a build step with @wordpress/scripts is recommended for modern development and to take advantage of JSX and other features.
How do I pass data from the server to the editor?
Use wp_localize_script to add a JavaScript object with the data. This is useful for things like dropdown options or default values that come from PHP.
Can dynamic blocks be used in the site editor (FSE)?
Yes, dynamic blocks work in the full-site editing context as long as they are registered correctly. They appear in the block library and can be used in templates and template parts.
Is it possible to update a dynamic block’s content without editing the post?
Yes, that’s the main advantage. The render callback can pull data from the database, an API, or any PHP logic, so the displayed content updates automatically when the underlying data changes.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.