WordPress 5.4 introduced the Block Variations API. The API can be used to create variations of blocks, which get listed as own blocks in the block inserter. An example from core are the social media buttons, that are all variations of the social link block.
A variation can predefine attributes of the block, in case of the social link block, for example, each variation defines the service
attribute with the identifier of the specific social network.
Like shown in the dev post on WordPress.org, variations are created like that:
variations: [
{
name: 'wordpress',
isDefault: true,
title: __( 'WordPress' ),
description: __( 'Code is poetry!' ),
icon: WordPressIcon,
attributes: { service: 'wordpress' },
},
{
name: 'google',
title: __( 'Google' ),
icon: GoogleIcon,
attributes: { service: 'google' },
},
{
name: 'twitter',
title: __( 'Twitter' ),
icon: TwitterIcon,
attributes: { service: 'twitter' },
},
],
Code language: JavaScript (javascript)
variations
is a key in the object that is passed to registerBlockType()
, like title
, edit
, attributes
, et cetera. Each variation gets a name
and a title
, which is displayed to the user.
Additionally, an icon can be set, and via attributes
we can set values for one or more block attributes. isDefault
specifies with variation should be the default. Moreover, the innerBlocks
key can be used to fill an InnerBlocks
component of the block with a set of blocks. That is used, for example, in the columns block, to create the different predefined column layouts.
With scope
, we can define in which area the variation should be available, but I did not quite understand what the options block
and inserter
do. Maybe block
means that the variation can only be used as part of another block. When leaving that option, both areas are set.
Currently, the variations do not appear as suggestions when using the /
command to add a new block. The pull request for that is merged, but part of Gutenberg 8.5, so will not be part of WordPress 5.5, which contains new Gutenberg releases up to 8.4.