Block Variations
Block variations are a great way to surface one block in multiple ways. The best example for block variations is the core embed block. There are all these different embed providers like YouTube, Vimeo, and many more. It would be a lot of duplicated code to create them all as individual blocks. Instead the block variations API allows you to define variants of a block. Each variant can set their own icon, title, and default values for its attributes & inner blocks.
Variations can also be used in a variations picker to choose between different predefined setups of a block. This is how the core columns block creates its initial setup state where the editor can choose from a predefined list of different variations.
Using Block Variations
Variations can be surfaced in three ways. They can be shown in the inserter, the block (like the core columns example), and in block transforms.
note
By default they are shown both in the inserter and the block.
Block variations can be declared during a block's registration by providing the variations
key with a proper array of variations, as defined below. In addition, there are ways to register and unregister a block variation
for a block, after its registration.
variations: [
{
name: 'wordpress',
isDefault: true,
title: __( 'WordPress' ),
description: __( 'Code is poetry!' ),
icon: WordPressIcon,
attributes: { providerNameSlug: 'wordpress' },
},
{
name: 'google',
title: __( 'Google' ),
icon: GoogleIcon,
attributes: { providerNameSlug: 'google' },
},
{
name: 'twitter',
title: __( 'Twitter' ),
icon: TwitterIcon,
attributes: { providerNameSlug: 'twitter' },
keywords: [ __('tweet') ],
},
],
An object describing a variation defined for the block type can contain the following fields:
info
The main difference between block styles and block variations is that a block style just applies a CSS class to the block, so it can be styled in an alternative way. If we want to apply initial attributes or inner blocks, we fall in block variation territory.
To add a block variation use registerBlockVariation()
.
Example:
import { registerBlockVariation } from '@wordpress/blocks';
registerBlockVariation( 'core/embed', {
name: 'custom',
attributes: { providerNameSlug: 'custom' },
} );
To remove a block variation use unregisterBlockVariation()
.
Example:
import { unregisterBlockVariation } from '@wordpress/blocks';
unregisterBlockVariation( 'core/embed', 'youtube' );