When to Use Dynamic Blocks
Dynamic blocks are ideal for:- Auto-updating content: Content that should change even if a post hasn’t been updated (e.g., Latest Posts block)
- Immediate code updates: When updates to block code (HTML, CSS, JS) should appear immediately across all instances without validation errors
- Server-side data: Content that requires database queries or server-side processing
How Dynamic Blocks Work
For dynamic blocks:- The
savefunction typically returnsnull - Only block attributes are saved to the database
- A server-side
render_callbackfunction generates the output - Validation is skipped since there’s no saved markup to validate
Basic Dynamic Block
JavaScript (Block Registration)
PHP (Server-Side Rendering)
Using Block Attributes
Dynamic blocks can save attributes to customize behavior.JavaScript with Attributes
PHP Render Callback with Attributes
Using ServerSideRender
The<ServerSideRender> component shows a live preview of the server-rendered output in the editor.
Server-side render is a fallback. Client-side rendering in JavaScript is always preferred as it’s faster and allows better editor manipulation.
Dynamic Blocks with InnerBlocks
If your dynamic block contains InnerBlocks, you must save them:Working with Block Supports
Dynamic blocks can use Block Supports for features like colors, spacing, and typography.JavaScript
PHP
Always use
get_block_wrapper_attributes() in your render callback to ensure Block Supports are properly applied.Common Patterns
Query-Based Block
User Data Block
Performance Considerations
- Cache when possible: Use transients or object caching for expensive queries
- Limit query results: Don’t query more data than needed
- Use efficient queries: Leverage WordPress query optimizations
- Consider pagination: For large datasets, implement pagination
Best Practices
-
Always use
get_block_wrapper_attributes(): Ensures Block Supports work correctly -
Escape output: Use
esc_html(),esc_url(),esc_attr()appropriately - Validate attributes: Check and sanitize attribute values
- Provide fallbacks: Handle cases where data isn’t available
- Use block.json: Define attributes and supports in block.json for better organization
Related Documentation
- Block Attributes - Managing block data
- Block Supports - Editor features
- Server Side Render - Component documentation
- InnerBlocks - Nested block content