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.
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 WordPress
wp_theme_json_data_blocks: “hooks” to the data provided by the blocks
wp_theme_json_data_userhooks on the data provided by the user
wp_theme_json_data_themehooks 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
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:
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:
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:
If you want me to prepare some examples just let me know.
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. 😉