pre_render_block Is the Wrong Hook for Term-Driven Template Part Swaps

pre_render_block Is the Wrong Hook for Term-Driven Template Part Swaps

Symptom. You add a pre_render_block callback that inspects the current post’s terms and returns a template part when a category matches. On the front end, the block renders the template part, but the terms are wrong, the block context is empty, and any downstream render_block filter you rely on for markup cleanup never runs. Nothing errors. The page just renders the wrong variant, or the right variant with the wrong data.

Trace. The callback fires. get_the_terms() returns something. The template part loads. The failure is not in the term lookup or the template loader. It is in the hook’s position in the render pipeline.

Root cause. pre_render_block is a short-circuit, not a render-stage filter. It runs before render_block_data and render_block_context, and a non-null return bypasses both plus the block’s own render callback and the render_block_{namespace/block} filter. For term-dependent template-part replacement, that is the wrong tool. The correct hook is render_block_data on core/template-part.

Fix. Use pre_render_block only for narrow, self-contained short-circuits keyed on $parsed_block['attrs'] and the global $post. Use render_block_data to swap a template part’s slug based on assigned terms. Use render_block or render_block_{namespace/block} for markup post-processing.

Verification. A Query Monitor hook trace, a WP-CLI term check, and a small REST request against the block renderer will show which hook fired, what it received, and whether the template part slug changed before rendering.

What pre_render_block actually receives and returns

The hook signature is documented as:

apply_filters( 'pre_render_block', string|null $pre_render, array $parsed_block, WP_Block|null $parent_block )

The first argument is $pre_render, default null. The second is the parsed block array: blockName, attrs, innerBlocks, innerHTML, innerContent. The third is the parent WP_Block instance for nested blocks, or null at the top level. The documentation states the purpose plainly: it “allows render_block() to be short-circuited, by returning a non-null value” (WordPress Developer Reference: pre_render_block).

That is the whole contract. It is not a filter for modifying block output. It is a filter for replacing the render call.

The ordering problem, in source order

The render_block() source makes the sequence unambiguous:

$pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block );
if ( ! is_null( $pre_render ) ) {
    return $pre_render;
}

$source_block = $parsed_block;
$parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block );

$context = array();
if ( $post instanceof WP_Post ) {
    $context['postId']   = $post->ID;
    $context['postType'] = $post->post_type;
}
$context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block );

$block = new WP_Block( $parsed_block, $context );
return $block->render();

Three consequences follow directly from that order:

  1. If your pre_render_block callback returns a string, render_block_data never runs for that block.
  2. render_block_context never runs, so the block’s context (including postId and postType) is never assembled.
  3. The WP_Block instance is never constructed, so the block’s own render_callback and the render_block_{namespace/block} filter never execute.

This is not an inference from reading the docs. It is the literal control flow of render_block() as published in the function reference. The Gutenberg issue tracker has the same observation from a different angle: “pre_render_block happens before you have access to render_block_context context or any modifications to the block via render_block_data” and “pre_render_block output also does not go through the render_block_${blockname} filter” (WordPress/gutenberg issue #68665).

If your term-dependent replacement depends on block context, or on a render_block_data modification made by another plugin, pre_render_block cannot see it. If your replacement depends on a downstream render_block filter to add classes, rewrite attributes, or sanitize markup, that filter will not run on the string you returned.

Why term lookup inside pre_render_block is fragile

get_the_terms() itself is not the problem. It is cached, and the documentation notes that it “won’t hit the database every time it’s called” (get_the_terms() reference). The problem is what “the current post” means at the moment pre_render_block fires.

The hook runs inside render_block(), which is called from do_blocks() during the_content processing, from the REST block renderer, from ServerSideRender requests in the editor, and from excerpt generation. In some of those contexts the global $post is the queried post. In others it is the post that owns the template, or a post inside a Query Loop, or nothing at all. A callback that calls get_the_terms( get_the_ID(), 'category' ) without checking the global will sometimes read the right post and sometimes read a different one, and it will not warn you.

The return contract is also easy to get wrong. get_the_terms() returns WP_Term[] on success, false if there are no terms or the post does not exist, and WP_Error on failure. A guard sequence that assumes an array will throw a warning on false and a fatal on WP_Error in PHP 8+. The safe pattern is:

$terms = get_the_terms( $post_id, 'category' );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
    return $pre_render; // leave rendering alone
}
foreach ( $terms as $term ) {
    // inspect $term->slug
}

That guard is necessary in any hook. It does not make pre_render_block the right place for the decision.

The template-part loading primitive

locate_template() searches the stylesheet directory, then the template directory, then wp-includes/theme-compat, and returns the template filename if one is located (locate_template() reference). It returns an empty string when nothing matches, so a non-empty return is the existence check you want before assigning a slug.

Two cautions from the same reference. First, locate_template() “does not prevent directory traversal attacks,” so never pass unsanitized user input as a template name. Second, for block themes the template part directory is not always parts; the WordPress developer news tutorial on dynamic template parts uses get_block_theme_folders()['wp_template_part'] to resolve it (Dynamically loading template parts in block themes).

The correct pattern: render_block_data on core/template-part

For term-dependent template-part replacement, the hook you want is render_block_data. It fires just before a block is rendered, receives the parsed block array, and lets you modify it before WordPress does anything with it. For core/template-part, the slug attribute tells WordPress which template part to load; change the slug and a different part loads. The WordPress news tutorial documents this pattern directly.

A minimal implementation for a single-post sidebar that varies by category:

add_filter( 'render_block_data', 'jv_render_template_part_data' );

function jv_render_template_part_data( array $parsed_block ): array {
    if ( ( $parsed_block['blockName'] ?? '' ) !== 'core/template-part' ) {
        return $parsed_block;
    }
    if ( ( $parsed_block['attrs']['slug'] ?? '' ) !== 'sidebar-post' ) {
        return $parsed_block;
    }
    if ( ! is_singular( 'post' ) ) {
        return $parsed_block;
    }

    $post = get_queried_object();
    if ( ! $post instanceof WP_Post ) {
        return $parsed_block;
    }

    $terms = get_the_terms( $post->ID, 'category' );
    if ( is_wp_error( $terms ) || empty( $terms ) ) {
        return $parsed_block;
    }

    $parts_dir = get_block_theme_folders()['wp_template_part'];

    foreach ( $terms as $term ) {
        $candidate = "sidebar-post-{$term->slug}";
        if ( locate_template( "{$parts_dir}/{$candidate}.html" ) ) {
            $parsed_block['attrs']['slug'] = $candidate;
            return $parsed_block;
        }
    }

    return $parsed_block;
}

Three properties make this the right hook rather than a workaround:

  • The callback always returns $parsed_block, modified or not. The tutorial states this as the key rule, because the filter runs for every block on the page.
  • The early returns bail on block name, slug, and query context before any term lookup. That keeps the cost of the filter low on pages with many blocks.
  • If no candidate template part exists, the original slug is left in place, so the default part loads. The fallback is free.

Because render_block_data runs before render_block_context and before WP_Block::render(), the modified slug is what the Template Part block actually uses. The block’s own render callback still runs, and downstream render_block filters still see the output.

What pre_render_block is legitimately good for

There is a narrow case where pre_render_block is the correct tool: a self-contained short-circuit for a specific core block, where the decision depends only on $parsed_block['attrs'] and the global $post, and where bypassing render_block_data, render_block_context, and render_block_{namespace/block} is acceptable because nothing else in the stack needs to touch that block.

An example is replacing a core/embed YouTube variant with a lightweight facade, where the decision is driven entirely by $parsed_block['attrs']['providerNameSlug'] and the replacement markup is generated from the block’s own attributes. The 10up Gutenberg guide demonstrates a facade replacement for the YouTube embed, though it uses render_block_core/embed rather than pre_render_block; the latter would skip the block’s own render callback and any downstream filters, which is a tradeoff you should make deliberately, not by accident (10up Gutenberg guide: Modifying the markup of a core block).

That recommendation is my own reading of the source order and the documented contract, not a pattern the WordPress documentation endorses. The documentation describes pre_render_block as a short-circuit and leaves the choice of when to short-circuit to the implementer.

Failure-mode checklist

Before shipping a render-hook callback, check each of these against the actual code path:

  • Returning a string from pre_render_block skips render_block_data, render_block_context, and render_block_{namespace/block}. If any of those need to run, use a different hook.
  • get_the_terms() can return WP_Error or false. Check is_wp_error() first, then empty(), then iterate. Do not assume an array.
  • locate_template() returns '' when nothing matches. Check the return before assigning a slug, or you will set an empty slug and the Template Part block will fall back or render nothing depending on version.
  • Template part slugs must exist in the theme’s parts directory. Use get_block_theme_folders()['wp_template_part'] rather than hardcoding parts, because block themes can use a different folder.
  • The global $post is not always the queried post. Inside a Query Loop, in REST block-renderer requests, and in excerpt generation, it may be something else. Use get_queried_object() with an instanceof WP_Post check when the decision is about the page being viewed.
  • Editor previews use a different path. render_block filters “have no impact on the behavior of blocks in the Editor” per the block filters reference, and ServerSideRender requests go through the REST block renderer. Test the front end and the editor separately.

Verification

Three checks will tell you which hook fired and what it saw.

1. Hook trace. With Query Monitor active, open the Hooks panel on a single post that has a category-specific template part. You should see render_block_data fire for core/template-part before the block renders, and you should not see your callback under pre_render_block if you moved it. If you left the callback on pre_render_block, the trace will show it firing before render_block_data and the block’s own render callback will be absent from the trace for that block.

2. Term check. Confirm the post actually has the term you expect, and that the term slug matches the template part filename:

wp post term list 123 category --fields=term_id,name,slug

If the slug in the output does not match the filename suffix in parts/sidebar-post-{slug}.html, the loop in the callback will not find a candidate and the default part will load. That is the intended fallback, but it looks like a bug if you expected the variant.

3. REST block renderer. Request the rendered block through the REST API to see what the server produces outside the theme’s template context:

curl -s -u user:app-password \
  'https://example.com/wp-json/wp/v2/block-renderer/core/template-part?context=edit&attributes%5Bslug%5D=sidebar-post'

The response shows the rendered HTML for that block in isolation. If the slug swap depends on is_singular( 'post' ) or get_queried_object(), the REST response will show the default part, because those conditions are not true in a block-renderer request. That is expected; it is also why the callback should bail early rather than assume the front-end context.

Decision rule

Pick the hook by what the decision depends on and what must run afterward:

  • pre_render_block — attribute-only short-circuit for a specific core block, where skipping render_block_data, render_block_context, and render_block_{namespace/block} is acceptable.
  • render_block_data — term-dependent template-part slug swaps, where the modified block data must reach WP_Block::render() and downstream filters must still run.
  • render_block or render_block_{namespace/block} — markup post-processing after rendering, where the block’s own output is the input.

The failure mode in the opening paragraph is not a bug in pre_render_block. It is a hook chosen for a job the hook was not designed to do. The source order is the specification; read it before choosing the filter.

FAQ

Can I use pre_render_block to replace a core block’s output with a template part at all?

Yes, mechanically: return a non-null string and render_block() returns it immediately. But the replacement will not pass through render_block_data, render_block_context, or render_block_{namespace/block}, and the block’s own render callback will not run. If any of those matter to your stack, use render_block_data for slug swaps or render_block for markup changes.

Why are the terms wrong inside my pre_render_block callback?

Most likely the global $post is not the post you think it is. pre_render_block fires inside render_block(), which is called from several contexts: the_content, the REST block renderer, ServerSideRender in the editor, and excerpt generation. Use get_queried_object() with an instanceof WP_Post check when the decision is about the page being viewed, and bail early when the context is not the front end.

Does render_block_data run for every block on the page?

Yes. The WordPress news tutorial states that the filter runs for every block, which is why the first thing the callback should do is bail early on block name, slug, and query context. The cost of the filter on a page with many blocks is dominated by those early returns, not by the term lookup, which only runs for the matching template part.

What happens if no category-specific template part exists?

Nothing changes. The callback leaves $parsed_block['attrs']['slug'] at its original value, and the default template part loads. That fallback is built into the pattern: you only create the parts you actually need, and the loop skips candidates whose files do not exist.

Is get_the_terms() safe to call inside a render hook?

It is cached, so repeated calls do not hit the database every time. The risk is the return type: WP_Term[], false, or WP_Error. Check is_wp_error() first, then empty(), then iterate. A callback that assumes an array will warn on false and fatal on WP_Error in PHP 8+.

Can I pass a user-supplied template name to locate_template()?

No. The function reference states that locate_template() does not prevent directory traversal attacks. If the template name comes from user input, validate that the resolved path is inside the active theme, parent theme, or wp-includes/theme-compat before loading it. In the pattern above, the candidate slug is built from a term slug returned by get_the_terms(), not from raw request input, but the same rule applies if you extend it.