Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active June 19, 2024 21:30
Show Gist options
  • Save RadGH/fd9b434c37698e8f2a75b557771e4d06 to your computer and use it in GitHub Desktop.
Save RadGH/fd9b434c37698e8f2a75b557771e4d06 to your computer and use it in GitHub Desktop.
Replace block page template dynamically using PHP
<?php
/**
* Before the block template is displayed, replace it with a different block template.
*
* IMPORTANT: You must create the block template through the editor: Templates > Add New
*
* @param string $template
*
* @return string
*/
function rs_replace_create_post_block_template( $template ) {
// Replace this conditional with your own logic to target a specific page or url:
if ( get_query_var('my_action') === 'create_post' ) {
global $_wp_current_template_id, $_wp_current_template_content;
// Use a block template from the theme
$block_template_slug = 'wp-custom-template-crm-create-post';
// Get the block template post in the database
$post = get_page_by_path( $block_template_slug, OBJECT, 'wp_template' );
if ( $post ) {
$_wp_current_template_id = wp_get_theme()->stylesheet . '//' . $block_template_slug;
$_wp_current_template_content = $post->post_content;
}
// Note that block themes do not replace $template. If we did that, the block template would not be parsed.
}
return $template;
}
add_filter( 'template_include', 'rs_replace_create_post_block_template' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment