Find out in this tutorial how to define template parts 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 theme.json file allows a degree of customization of a WordPress theme that is worth getting familiar with.
That’s why I’m publishing a series of tutorials focused on how it works and especially how you can customize it to your liking.
In this case, we are going to see how to define the template parts (header, footer…) of a theme.
Instructions for defining the template parts of a WordPress theme
1. Creating custom templates
The first thing you have to do if you want the template parts to be displayed in the template editor, is to create the template parts in question. Logical, isn’t it?
For this example we are going to use one template part which is the header and another one which is the footer.
To create them just 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 that, add the following code :
To see this and another 1097 code snippets of this website, login or subscribe here.
With this code you would be defining two new template parts, a header and a footer.
These are the properties you can modify:
name
: the name of the template part file.title
: the title that will be displayed when searching for the block in the template editor.area
: area in which it will be displayed:header
: headerfooter
: footeruncategorized
: if you want to use an area other than the two above. Handy if you want to use post listings.
You can add different types of headers or footers, for example Twenty Twenty-Two theme adds several header options:
"templateParts": [
{
"name": "header",
"title": "Header",
"area": "header"
},
{
"name": "header-large-dark",
"title": "Header (Dark, large)",
"area": "header"
},
{
"name": "header-small-dark",
"title": "Header (Dark, small)",
"area": "header"
},
{
"name": "footer",
"title": "Footer",
"area": "footer"
}
]
B. Modify the theme.json file
In case your theme already has a theme.json file you can define the template parts in it. To do this look for the "templateParts"
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. Interface in the block editor
Once you have added this snippet, either by adding a new theme.json file or by modifying an existing one, you will see these template parts appear in the template editor.
Conclusions
Now you know how to define template parts in any WordPress theme using 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. 🙂