Add theme.json block stylesheet support + bug fix#2
Conversation
kadamwhite
left a comment
There was a problem hiding this comment.
Before approving, I want to understand the specific timing issue requiring changing the hook to render_block, and to understand the use case for registering blocks in theme.json rather than using the existing block.json properties?
| */ | ||
| add_filter( | ||
| $hook_name, | ||
| 'render_block', |
There was a problem hiding this comment.
Can you explain the bugfix? The original plan to hook into render_block_ was deliberate to substantially reduce the number of times we need to run these checks, on large documents — I'd love to know more about the timing issue that's alluded to here.
There was a problem hiding this comment.
The stylesheet loading was working for other blocks, but when I got to the cover block, the styles weren't being enqueued. With Claude's help, I discovered that they only took effect for the second block of the same block style.
Here's Claude's explanation:
The original code hooked into render_block_{block_name} at priority 10, but that made it impossible for wp_enqueue_block_style() to actually enqueue the stylesheet for the current block.
Here's why:
wp_enqueue_block_style() works by adding its own callback to the generic render_block filter at priority 10. When a block renders, that callback checks whether the style is queued and injects it.
The original code called wp_enqueue_block_style() from inside a render_block_{block_name} hook — but WordPress fires the generic render_block hook before the block-specific render_block_{block_name} hook. This means by the time our callback ran and called wp_enqueue_block_style(), the render_block hook had already fired for that block, so wp_enqueue_block_style()'s own internal callback would never run for it. The style effectively got registered too late — only on the next block of that type, if one existed.
The fix switched the hook from render_block_{block_name} (priority 10) to render_block at priority 1. Since priority 1 fires before wp_enqueue_block_style()'s own priority-10 callback on the same render_block hook, our code now calls wp_enqueue_block_style() while there's still time for it to do its work on the current block. The block name check ($block_name === $block['blockName']) was also added to the condition to compensate for no longer using the block-specific hook.
|
For the change to look for stylesheets in theme.json, that was so that we can use media and container queries for the default block style/all block styles for the block. This was Claude's idea of how to do it - I'm not attached to it, if we can find another way to use query-based styles that only load when the block is on the page. |
get_extended_block_stylesheetsfunction to look through the theme.json for stylesheet referencesafter_setup_themeaction to register those stylesheetsNote: this is vibe-coded and human reviewed.