WordPress.org

WordPress Developer Blog

Snippet: How to register a block variation but hide it from the inserter

Snippet: How to register a block variation but hide it from the inserter

When defining a custom block, the inserter property in block.json can be used to control if the block is available to be inserted by the user or if it can only be added programmatically.

In some cases, a custom block is overkill, and a block variation is a better solution. For example, a user in the outreach channel wanted to add an attribute to a block that was only used in a template and, based on the existence of that attribute, add some custom functionality.

This is a perfect scenario to use a block variation. The issue was that they couldn’t hide the variation from the inserter.

After some digging, it is possible to hide the block by setting the scope property to block in registerBlockVariation. The following code registers the paragraph-red block variation for the Paragraph block, but it’s not available to users in the Editor.

import { registerBlockVariation } from '@wordpress/blocks';

registerBlockVariation( 'core/paragraph', {
	name: 'paragraph-red',
	title: 'Red Paragraph',
	attributes: {
		textColor: 'vivid-red',
	},
	isActive: [ 'textColor' ],
	scope: [ 'block' ],
} );

This value is used for blocks like the Columns and Query blocks to filter specific block variations. These variations are passed to the experimental BlockVariationPickercomponent which handles displaying the variations and allows users to choose one of them. For variations of other blocks, the scope property is a great workaround to hide them from the inserter.

Relevant links

Props to @ndiego and @greenshady for reviewing this snippet

Leave a Reply

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