Find out in this tutorial how to define custom templates in a WordPress theme using the theme.json file.
WordPress 5.8 introduced the theme.json file which is one of the key pieces on which block themes or FSE (Full Site Editing) are based.
The good thing is that the theme.json file can be used in classic themes so it’s a good idea to get familiar with it.
That’s why I’m publishing a series of tutorials focused on how it works and how you can customize it to your liking.
In this case, we are going to see how to define custom templates for a theme
Instructions for defining custom templates in a WordPress theme using theme.json
1. Create the custom templates
The first thing you have to do if you want custom templates to be displayed in the editor, is to create the templates. Logical, isn’t it?
For this example we are going to use a template that is blank (it will only show the content, no header, no footer, no sidebar…) and another one without a title.
To create them you only have to use the template editor.
2A. Create the theme.json file
In case the theme does not have it, you have to create a file called theme.json and place it in the root of your theme.
Once you have done this, add the following code :
With this code you would be adding to the editor the two new templates, one blank and one untitled.
These are the properties you can modify:
name: the name of the custom template file.
title: the title to be displayed in the dropdown.
postTypes: the type of content that the template can use
2B. Modify the theme.json file
In case your theme already has a theme.json file you can add or remove custom templates. To do this look for the
"customTemplates" section (if it does not exist create it at the same level as
"settings") and change the content between square brackets ([ ]) taking into account the properties discussed above.
3. Block editor interface
Once you have added these lines, either by adding a new theme.json file or modifying an existing one, you will see a new section called “Template” appear in the editor.
In it you will find a dropdown that will display the custom templates you have defined in the previous steps.
Now you know how to define custom templates in any WordPress theme using the theme.json file.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂