Nifty Code #2: Block parents

In my previous post, I described using InnerBlocks to create a template and restrict the blocks allowed in “parent block”. This post is kind of the reverse 🙂

When writing the Recipe Block, I wanted to allow for repeating fields of ingredients and directions. I thought the best way for this would be to make each section blocks as well, but I didn’t want them available to the editor in general.

Luckily, one of the configuration settings you can pass to registerBlockType is parent – which is an array of blocks.

registerBlockType( 'ryelle/recipe-meta', {
	title: __( 'Recipe Meta', 'rmb-recipe-block' ),
	parent: [ 'ryelle/recipe' ],

The block inserter will check against this setting and the current parent block (the post itself, or a block that uses InnerBlocks), before deciding whether to show this block in the list.

If you followed the last post, and set up your block with InnerBlocks, you can use that block’s name as the parent, and like magic it will only be available inside your container block.

Screenshot of the block insert when inside the recipe block. Directions, Ingredients, and Meta are all available here, but not at the top-level block inserter.

So now you can build repeatable, movable fields as “sub-blocks” of a parent, without worrying about it cluttering the blocks list, or what should happen if someone tries to use it at the top-level of a post.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: