Learn in this tutorial how to create a block template for posts in a classic WordPress theme.
If you haven’t yet started to use block themes (FSE) but want to take advantage of the block editor’s functionality in a classic theme, block templates are a great option to do so.
For example, WordPress allows you to generate a predefined block template and associate it with a content type.
This way, if you or your client always use the same structure in your blog posts, you only have to create a template in which to enter information.
It will be better to understand with an example. Imagine that the entries of a website always follow the following structure:
- Introduction paragraph
- Heading 1
- Paragraph with the content of section 1
- Heading 2
- Paragraph with the content of section 2
- Heading 3
- Paragraph with the content of section 3
- Paragraph with the content of the conclusions
In this case you have the option of creating a template with the necessary blocks so that every time you generate a new entry the author only has to worry about adding the content.
Sounds good, doesn’t it?
This would be the result of adding a new entry:
Find out how to do it below.
Snippet to create a block template for posts in a classic WordPress theme
Add the following code at the end of functions.php or in your functionality plugin:
In the code you use the
get_post_type_object function to get the content type object you choose, in this case posts, and tell it the blocks you want the template assigned to that type of posts to contain.
As you can see, the structure of the block template is quite simple.
To add new blocks you have to know the “name” of the block. For example, to insert the paragraph one it is:
Here you have the list with all the native WordPress blocks:
You can also use blocks created by other plugins, you just have to know the name with which they have been registered. You can take a look at the tutorial on how to get a list of all the blocks registered in a WordPress installation.
Once you know the internal name of the blocks you want to use, you have the possibility to add content in the blocks using the block attributes. For example,
'content' or insert filler content by typing
And again I invite you to modify the text of both according to your needs. Please note that not all blocks accept both options.
Note: by default, the header block adds a H2, if you want to introduce a header H3, H4, H5… you can do it in the following way:
[ 'core/heading', [ 'level' => 3, 'content' => 'Heading H3', ] ],
If you have a defined structure that is repeated in your blog posts, creating a block template is a fantastic way to save time
Even more so if you do it for your client, since it considerably facilitates the use of the web.
And now you know how to do it in a simple way. Just use this code as a starting point and adjust it to the needs of the project