Replacing the Current Block Template Dynamically in WordPress

In this guide, we will explore how to dynamically replace the block template in WordPress based on certain conditions. Our goal is to allow users to create and select custom block templates through the WordPress Editor and dynamically apply them based on specific query variables. Let’s dive into the details!

1. Create a Template Through the Editor

Instead of creating a template dynamically, we will allow the user to create a template directly through the WordPress Editor. This approach ensures that new templates are registered and visible in the site editor.

User created templates are stored in the database as a post, with the post type “wp_template”. If you want to create a template automatically instead, try inserting the post dynamically too. If you manage to do it this way and would like to share your result, drop a comment below!

2. Replace the Block Template Dynamically

To replace the block template dynamically, we will use the template_include filter. We will check for our custom query variable and swap the block template accordingly. We won’t actually change which template is included by that filter. The template_include filter fires just before the block template is displayed, so it’s the perfect time to add our block template.

Hook into template_include

The function below piggy-backs off the “template_include” filter in order to replace the current block template used on the page.

I hope that WordPress will in the future add actions or filters to allow you to programmatically change the block template. In it’s current state

public function replace_block_template($template) {

// Check if we should load the block template on this page
// (Add your own condition here, this is just an example)
if ( get_the_ID() === 123 ) {


// These global variables store the current block template
global $_wp_current_template_id, $_wp_current_template_content;

// Get the theme slug, to use with the ID
$theme_slug = wp_get_theme()->stylesheet;

// Insert your custom template's slug here:
$template_slug = 'crm-create-post';

// Generate the block ID using those two slugs
$block_template_id = $theme_slug . '//' . $template_slug;

// Locate the template in the database
$post = get_page_by_path($template_slug, OBJECT, 'wp_template');

// If the template exists, replace the existing block template
if ($post) {
$_wp_current_template_id = $block_template_id;
$_wp_current_template_content = $post->post_content;
}


}

return $template;
}
add_filter('template_include', 'replace_block_template');

Summary

By following these steps, you can create a system in WordPress that allows users to create and dynamically apply custom block templates based on your own conditions. This allows you to create a more dynamic website.


Comments

Leave a Reply

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