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
.
This 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 block.json
.)
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 block.json
file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"name": "my-namespace/my-block",
"title": "NAME OF MY BLOCK",
"description": "BLOCK DESCRIPTION",
"category": "my-category",
"keywords": [ "keyword 1", "keyword 2" ],
"attributes": {
"title": {
"type": "string"
},
"content": {
"type": "string"
},
"showContent": {
"type": "boolean"
}
},
"script": "file:relative/path/to/block-registration-script.js",
"editorStyle": "file:relative/path/to/editor-styles.css",
"style": "file:relative/path/to/front-end-styles.css"
}
Key takeaways
- Make sure all of the block information in
block.json
exactly 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.json
requires 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.json
in 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.