Skip to content

How to dynamically load template parts in block themes #469

@bph

Description

@bph

Discussed in #459

Originally posted by justintadlock March 25, 2026
Here's a quick snippet I used to dynamically load a category-based sidebar template for single posts:

add_filter('render_block_data', 'themeslug_render_template_part_data');

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

	$post = get_queried_object();

	if (! $post instanceof WP_Post) {
		return $parsedBlock;
	}

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

	foreach (get_the_category($post->ID) as $category) {
		$slug = "sidebar-post-{$category->slug}";

		if (locate_template("{$partsDir}/{$slug}.html")) {
			$parsedBlock['attrs']['slug'] = $slug;
			return $parsedBlock;
		}
	}

	return $parsedBlock;
}

Essentially, it looks for parts/sidebar-post-{category}.html and falls back to parts/sidebar-post.html, allowing theme authors to create sidebars based on the post category.

There's loads of things that you can do with this, though. It's not limited to sidebars and could be realistically used to replace any template part based on the given data.

This is just an easy snippet, but I could see it being wrapped up into a longer tutorial.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions