Discover in this tutorial how to check if a WordPress theme uses the theme.json file and make sure to run a function (or any code) only if it has it.
WordPress 5.8 introduced the theme.json file, which is one of the key building blocks of block themes.
The good thing is that the theme.json file can be used in classic themes, that’s why I prepared a tutorial explaining all the potential it offers.
More recently, in WordPress 6.1 several filters were introduced to access the theme.json file:
wp_theme_json_data_default
: it “hooks” to the data provided by WordPresswp_theme_json_data_blocks
: “hooks” to the data provided by the blockswp_theme_json_data_user
hooks on the data provided by the userwp_theme_json_data_theme
hooks into the data provided by the theme
This allows this file to be fully extensible. But if you are developing a plugin or similar, it is advisable to check if this file exists or not where the code is going to be executed and use a conditional so that it only does so if there is one.
As you can imagine, this conditional is the perfect candidate to combine with the filters I mentioned above.
In this tutorial you will learn how to do it:
Code to check if a theme has a theme.json file
To detect if the theme has a theme.json file you can use the function wp_theme_has_theme_json()
.
This would be a simple example of how to display if it has one or not using a shortcode.
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 997 code snippets of this website, login or subscribe here.
This is a simple example in which you detect if the theme has a theme.json file or not and have it displayed to you. But this is not the important part.
The idea is to use that information to make the execution of a code conditioned by the type of theme used in question.
The function could be something like this:
To see this and another 997 code snippets of this website, login or subscribe here.
As you can see, first you detect if the theme has a theme.json file and then you execute one code or the other conditionally.
To adapt these examples to your convenience you only have to add the code that you want to be executed depending on the theme type.
As I said at the beginning, this function can be very practical to combine with the following filters:
wp_theme_json_data_default
wp_theme_json_data_blocks
wp_theme_json_data_user
wp_theme_json_data_theme
If you want me to prepare some examples just let me know.
Conclusion
Now you know how to detect if a WordPress theme has a theme.json file (or not) and run different codes depending on the theme type.
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉