Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Block plugins and WordPress hooks
    WordPress 6.4 Block Hooks WordPress Hooks block.json hooked_block_types WordPress block plugins automatic block insertion Site Editor WordPress development


Block plugins and WordPress hooks


Here is a summary of how block plugins can use WordPress hooks, specifically the new Block Hooks feature introduced in WordPress 6.4:

1. Block Hooks Principles:
- Automatic Placement: Blocks can automatically position themselves when another block is added to the content, eliminating the need for manual insertion.
- Visibility and Control: The inserted block is visible in the editor, and users retain control over its automatic insertion, allowing for a customized editing experience.

2. Limitations and Considerations:
- Block Hooks only work in unmodified templates, template parts, and patterns provided by themes. They do not function in post content, modified templates/parts, or user-generated patterns.
- As of WordPress 6.4, automatic insertion does not work with blocks that have a custom save function, as it may result in block validation errors. Developers should use Dynamic blocks for compatibility.

3. Two Ways to Hook Blocks:
a. Using `block.json`:
- Provides a simple way to hook a third-party block, but with limited flexibility.
- The `blockHooks` property in `block.json` allows specifying the position of the hooked block (before, after, first child, last child).
b. Using the `hooked_block_types` filter:
- Offers more flexibility compared to `block.json`, allowing conditional hooking based on the template, template part, or pattern.
- The callback function for `hooked_block_types` receives parameters like the hooked blocks, position, anchor block, and context.

4. Considerations for Developers:
- Hooked blocks will appear in the Site Editor, giving users control over their placement. Developers cannot force a block's position if the user wants to move it.
- Hooking static blocks (with custom save functions) is not recommended, as it may cause block validation errors. Dynamic blocks are the preferred choice for Block Hooks.
- Developers should ensure their hooked blocks are compatible with the current WordPress version and its Block Hooks API.

In summary, the new Block Hooks feature in WordPress 6.4 and beyond provides a powerful way for block plugins to automatically insert their blocks in specific locations, while still allowing users to control the placement of those blocks within the Site Editor.

Citations:
[1] https://github.com/WordPress/gutenberg/issues/54904
[2] https://kinsta.com/blog/wordpress-hooks/
[3] https://essential-blocks.com/block-hooks-everything-you-need-to-know/
[4] https://www.youtube.com/watch?v=ezPHiyhhaoQ
[5] https://developer.wordpress.org/block-editor/reference-guides/packages/packages-hooks/