WordPress Block Hooks API: Auto-Insert Blocks into Templates

WordPress 6.4 introduced the Block Hooks API, which lets you automatically insert blocks into block templates, parts, and patterns without editing them directly. This is the block-era replacement for the old dynamic_sidebar / widget hack.

Problem: WordPress automatically inserts some built-in blocks — like the Comments block — into templates at render time, but there is no documented way for third-party blocks to do the same without editing every template file manually.

Solution: Use the Block Hooks API (introduced in WordPress 6.4) — add a block_hooks key to block.json to declare where your block should be auto-inserted relative to an anchor block. For dynamic insertion with conditions, use the hooked_block_types or hooked_block PHP filters.

The examples below register a block with a block_hooks key so WordPress inserts it before every core/post-title block, and also show how to do the same thing programmatically via the hooked_block_types filter for conditional logic.

// In your plugin or functions.php
// Declare block hooks inside block.json
// block.json:
{
  "name": "myplugin/reading-time",
  "title": "Reading Time",
  "blockHooks": {
    "core/post-title": "before"
  }
}

// Supported positions: before | after | firstChild | lastChild
// Works for static templates (.html), block patterns, and template parts.
// The block is inserted ONLY when the surrounding template is loaded;
// it does NOT modify the DB content of individual posts.

For dynamic insertion with custom conditions use the hooked_block_types filter:

add_filter( 'hooked_block_types', function( $hooked_blocks, $position, $anchor_block, $context ) {
    // Insert our block after core/post-content only on single posts
    if ( 'after' === $position
        && 'core/post-content' === $anchor_block
        && $context instanceof WP_Post
        && 'post' === $context->post_type
    ) {
        $hooked_blocks[] = 'myplugin/author-box';
    }
    return $hooked_blocks;
}, 10, 4 );

// Modify the hooked block's attributes before insertion:
add_filter( 'hooked_block', function( $parsed_hooked_block, $hooked_block_type, $position, $parsed_anchor_block ) {
    if ( 'myplugin/author-box' === $hooked_block_type ) {
        $parsed_hooked_block['attrs']['showAvatar'] = true;
    }
    return $parsed_hooked_block;
}, 10, 4 );

NOTE: Block Hooks run at render time and respect user edits — if the user manually removes the hooked block from a template, WordPress respects that choice and won't re-insert it.

Leave Comment

Your email address will not be published. Required fields are marked *