Building WordPress block variations

Block variations, a new method to extending the WordPress block editor, recently landed in WordPress 5.4. The newly introduced Block Variations API provides alternate configurations of a block that are selectable when a block is first added to a page.

Now block variations can be big deal, if properly adopted. It is important to note that block variations differ quite a bit from block style variations–and even block patterns.

While block style variations change the look and feel of a block – block variations change the substance of a block; configuring it in a meaningful fashion.

I agree, the lingo can be confusing – I actually opened an issue on GitHub to help clear this up.

The idea of block variations is not new by any means. There are blocks in core, and third-party plugins, that have employed a similar approach for some time now. The CoBlocks Row block sported an earlier form of variations back in 2018, where you could select a variant of the block using different columns and widths layouts. The difference with variations in WordPress 5.4 is that we now have a consistent experience and a formal API for which developers may leverage to extend any block that supports variations. Pretty nifty

When you add a block that uses variations, you’re presented with a placeholder that serves as a way to quickly start with a few precise configurations of that particular block.

There are actually two blocks within core WordPress that leverage block variations: the Columns and Social blocks. Below is an example of how variations are displayed within the core Columns block.

This experience presents five initial variants to kick off the block with, instead having to add the block, configure the number of columns, then manually adjust the column widths. With variations, we can add any of these column layouts with a single click. This saves a ton of time and effort. While this works great for the Columns block, the API was built to be leveraged in any block that uses variations–including third party blocks of course. So early on, we adopted the Block Variation API into the CoBlocks form block, to give folks a choice between a traditional contact form, RSVP form, or appointment booking form.

Once a variation is selected, the form variant is instantly added to the page, making a minutes long process cut down to milliseconds.

Registering custom block variations

Variations are fantastic, but what if you’re looking to extend a block which leverages block variations? Thankfully the Block Variations API makes this relatively simple to do. Registering variations is actually quite similar to general block registration. You’ll need the name of the block to extend, a title for the variant, description, icon, and a few other properties to establish the variant’s configuration. Here’s an example of extending the CoBlocks Form block by adding an “Event Registration” form variation, based on a typical WordCamp registration form:

wp.domReady( function() {
	wp.blocks.registerBlockVariation( 'coblocks/form', {
		name: 'event-registration',
		title: 'Event Registration',
		icon: '<svg height="48" viewBox="0 0 48 48" width="48" xmlns="http://www.w3.org/2000/svg"><path d="m18 10h-14v2h14zm2-8h-1v-2h-2v2h-12v-2h-2v2h-1c-1.11 0-1.99.9-1.99 2l-.01 16c0 1.1.89 2 2 2h18c1.1 0 2-.9 2-2v-16c0-1.1-.9-2-2-2zm0 18h-18v-13h18zm-5-5h-6-5v2h11z" transform="translate(13 14)"/></svg>',
		innerBlocks: [
			[ 'coblocks/field-name', { label: 'Full name', hasLastName: true } ],
			[ 'coblocks/field-email', { required: true } ],
			[ 'coblocks/field-radio', { label: 'How do you use WordPress?', required: true, options: [ 'I write', 'I design', 'I develop', 'I manage', 'I am new to WordPress!'] } ],
			[ 'coblocks/field-checkbox', { label: 'I’m on a gluten-free diet', options: [ 'Yes', 'No' ], required: true } ],
			[ 'coblocks/field-checkbox', { label: 'We can also provide specially prepared meals if needed', options: [ 'Kosher', 'Halal', 'None' ] } ],
			[ 'coblocks/field-textarea', { label: 'Any other dietary needs?', required: true } ],
			[ 'coblocks/field-checkbox', { label: 'Do you agree to follow the event Code of Conduct?', options: [ 'Yes' ] } ],
			[ 'coblocks/field-submit-button', { submitButtonText: 'Register' } ],
		],
		scope: [ 'block' ],
	} );
} );

In this new variation, I am including a name field, email, a textarea for dietary needs, and a checkbox signifying that our attendees will follow the code of conduct. The submit button text is also set initially to “Register.” While all of these blocks/settings are configurable through the block itself, I am simply setting up the defaults for the event registration form. You’ll also need to enqueue the script of course:

function block_variation_example_enqueue() {
    wp_enqueue_script(
        'block-variation-example-script',
        plugins_url( 'index.js', __FILE__ ),
        array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' ),
        filemtime( plugin_dir_path( __FILE__ ) . '/block-variation-example.js' )
    );
}
add_action( 'enqueue_block_editor_assets', 'block_variation_example_enqueue' );

Now you’ll have a new variation added to the end of the list of variations, and when selected, a full fledged event registration form that could be used as the standard for WordCamps:

Having this variation will make it much easier for the end user to add a form for registering event attendees – instead of having to build out the form every time its used.

I’m excited about what block variations can bring to the table in terms of versatility and user experience. The idea that a block can be pre-configured, then applied to the page in a single click is revolutionary, and I expect we’ll see all sorts of block variations pop up over time. I’m all for improving the extensibility of the block editor, and block variations do just that. How will you leverage variations?

Responses

  1. Joakim Avatar

    Awesome, thanks for the tip!

  2. Dimiter Kirov Avatar

    This is exciting. Everything that extends something”s functionality offers plenty of new opportunities and I’ll definitely inspect carefully block-variation-example.js code on GitHub. but as I said yesterday I’m not a developer so my comment now is absolutely off this topic but it’s really important to me: sidebars?
    Are they dead? As I see You,Mr Tabor , just like many other core contributors use a theme without sidebars.
    All widgets are ported into blocks now. For example, CoBlocks offer a widgetized area block. Other 3 rd party blocks plugins, though not many, too. However , but bear in mind that I’m not in touch with the recent updates to Gutenberg project, the opposite – porting all blocks to widgets ,is still not accomplished. I’ll repeat: my information is not up to date on that matter. I’ve found a way around but I’m curious and a bit anxious about the future of sidebars.
    The real problem actually is that the only way for You to reply to me is not via a comment reply but via a handwritten email.
    Anyway have a great day!

  3. Victor Ramirez Avatar

    I like that block variations is separate from block styles.

    Currently giving people style variations for headings, quotes, testimonials, etc.

    This will be great for creating varying CTA modules for marketing sites.

  4. Jerome Toole Avatar
    Jerome Toole

    Hi Rich, this is extremely useful, thanks. Currently looking at using it to set up a group block as a styled CTA block. (set a background, add a header, paragraph and buttons)

    One thing I am confused about is that I don’t get the interface you have in your screenshots. My variations show up within the normal new block search interface instead. If I click on the core block, I don’t get a variations picker?

    Is there some other api for adding this picker interface? I’ve had a search but couldn’t find anything.

    1. Rich Tabor Avatar

      Correct, the variations need to be added to the block registration in order to provide a picker placeholder view. Here’s how we do it in the CoBlocks Form block, registered here.

      1. Chris Davies Avatar
        Chris Davies

        Hi Rich, thanks for the tutorial on this – really helpful. Like Jerome I am not able to get the placeholder/picker to show up in a custom block that I am writing. Do I have to add all the placeholder etc myself?

Leave a Reply

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