I needed to override one of the theme TwentyTwentyTwo template from a custom plugin, and I wanted to use one of Gutenberg’s blocks.
I see that in the templates files blocks are used by just writing the corresponding html comment.
So I tried editing the template/single.html file in
<!-- wp:post-title /-->
<!-- wp:custom-block-i-defined /-->
<!-- fest -->
<div>Test</div>
and created a file plugin.template.html with the same content in my plugin.
When I visit a single page with the theme’s template, it renders the blocks fine, but if I do so using
add_filter( 'template_include', 'override_template' );
function override_template( string $template ) {
return 'path/to/the/plugin.template.html';
}
the rendered page only contains the Fest div, but inspecting the page reveals the comments that didn’t become blocks.
Am I using a wrong filter? Should I call some function to "hydrate" the blocks?
2
Answers
Similarly, I wanted to deliver an archive HTML template in my plugin. So I hope this helps.
The filter
template_include
didn’t cut it and after running debug and tracing the template loading route I found a solution with the filterget_block_templates
.Here’s a simplified version of the key parts of my plugin code:-
When the template was in the template folder of the child theme the render was fine, but from inside the plugin I had to force the theme name into the template. To avoid the header and footer failing to display. I was getting
Template part has been deleted or is unavailable: header
Hence the
str_replace
.Using this method means I can just deploy a plugin and be totally theme agnostic, but I now can’t edit the template from the site editor. The template needs to be in the theme folder to do that.
My archive-ale.html template:
My solution, above, is one way to ADD an HTML template residing in the plugin folders.
To override an existing theme template use the same filter but find the template slug to override and then overwrite the content property, or remove it completely from the array and append your new one.
I’m still wondering if a template from a plugin should really be copied to the theme template folder on activation so that the user can then use the site editor to make further modifications.