Creating block.json for a WordPress block
I have been creating custom WordPress blocks since Gutenberg was in beta, though the vast majority are for work. But this week, I added my very first block to the WordPress block directory. (Hooray for my Color Palette!!)
Anyone can create a plugin that adds a block to your WordPress site. However, developers need to go through a second step to add that block plugin to the block directory. The plugin is analyzed to make sure that it meets some basic requirements, one of which is the existence of a file called
block.json file allows the block directory to be able to find your block. So, it’s kind of important. It is autogenerated for you if you create your block using the npm command outlined in WordPress’s create a block tutorial.
Easy peasy, but if you are anything like me and enjoy developing from scratch, figuring out the exact requirements for the attributes that go into
block.json is difficult, because there is no documentation on its requirements. (It took me four attempts to get it right.)
Where do I even start?
Since the entire purpose of
block.json is to register your block with the block directory, much of information in this file comes from the block registration function. The block directory support page lists a few single block plugins as examples.
I used the code from several of those plugins as a resource. (The Apple Maps block by 10up has a particularly detailed example of
Side note to new developers: Learn to learn from other people’s code. It’s the best!
File anatomy: A mostly complete example
The following example is the structure I used for my Color Palette block. Feel free to also take a look at my real
- Make sure all of the block information in
block.jsonexactly matches the information in the block registration script. This includes the name, title, description, category, keywords (if applicable), and attributes.
- Include all of the attributes, their types, and any default values.
block.jsonrequires at least one script or style to be defined, so define as many of these as you have.
- The path to the script and style files are file paths that are relative to the location of
block.jsonin your repository.
I have no idea if this is 100% correct and/or complete, but it is correct/complete enough to register my block with WordPress and successfully add my block to a site.