WordPress 5.4 introduces a feature called Block Variations, which can greatly improve website building efficiency. This article will explore this feature in depth and explain how it differs from Block Styles and how block variants are created and applied.
What exactly is a block variant?
Block variants allow developers to define different instances of existing blocks. For example, a reference block may have three different display methods on your website, so you can create a block variant for each display method to achieve a different style. This sounds very similar to the block style, but the concept of the variant goes a step further, as we'll see later.
How are block variants different from block styles?
This is a good question. Block variants appear in the inserter as separate blocks with unique names (and optional icons) and can be pre-populated with custom properties and internal blocks.
Block styles are designed to change the appearance of blocks. In fact, block style is an advanced way to add custom classes to blocks using block options in the article editor.
When you use them in the article editor, the difference becomes clear. Suppose we register a new block style called "Fancy Quote". We can do this by extending the core "Quote" block, as shown in the example in the following block editor manual:
<code>wp.blocks.registerBlockStyle( 'core/quote', { name: 'fancy-quote', label: 'Fancy Quote' }, );</code>
This adds a .is-style-fancy-quote
class to the settings of the "Quote" block in the article editor.
While it sounds like it will do the same thing (actually it can do it too), block variants can be used to pre-populate custom properties (including custom classes) and internal blocks. They are actually registered as separate blocks.
Let's take a closer look at what the API and block variants can do.
Create block variants
The API for registering block variants is very similar to the block style we just saw:
<code>wp.blocks.registerBlockVariation( 'core/quote', { name: 'fancy-quote', title: 'Fancy Quote', }, );</code>
The registerBlockVariation
function accepts the name of the block (in this case core/quote
) and an object (or object array) to describe the variant.
The above code doesn't do much by default, but it does add "Fancy Quote" to the list of available blocks.
To make the most of the variation, we need to provide more details in the object that describes it. These details are listed in the Make WordPress
article, and I will share them here and provide additional comments.
-
name
– The unique and machine-readable name of the variant. According to the examples on Github and Make articles, the best practice is to use kebab-case to name variants. -
title
– a human-readable variant title. This is what is displayed under the icon in the inserter. -
description
– Detailed variant description. Also displayed in the inserter. If empty, the default block description is used. (Optional) -
icon
– variant icon. Can be a Dashicons slug, SVG, or an object. Follow the same declaration pattern as inregisterBlockType
. (Optional) -
isDefault
– Indicates whether the current variant is the default variant. Default is false. In our example, if we set it to true, the "Fancy Quote" block will be the only Quote block available in the inserter. (Optional) -
attributes
– Override the value of the block attribute. These are block-specific. For example, you can set a level for the "Heading" block, or set a height for the "Spacer". -
innerBlocks
– The initial configuration of nested blocks. Only available for blocks that allow internal blocks first, such as Columns, Cover, or Group. We will cover this in one of the examples. (Optional) -
example
–example
provides structured data for block previews. You can set it toundefined
to disable the displayed block type preview. This is the same as theexample
field inregisterBlockType
. (Optional) More information is available for this parameter. -
scope
– A list of scopes that variants apply. If not provided, all available ranges are assumed. Available options includeblock
andinserter
. We will cover this in detail in one of the examples.
Many people may wonder why we need this extra layer of abstraction. Let me try to answer this question with a few use cases (from one of my recent projects).
Use case: buttons of different widths
Suppose your design system has two types of buttons: "Fill" and "Outline".
Fortunately, these are the default styles of buttons in WordPress. No new styles or editing the editor is required. You just need to write some CSS for each style. Life is beautiful and everyone is happy.
However, you look at the design specifications again and see a small change. The buttons are available in three widths: "Regular", "Wide", and "Full".
Damn it! You're a little frustrated because you have two options now:
- Write two additional classes for the new button size (for example,
.is-wide
and.is-full
) and teach the client to add these classes using the Advanced panel in the editor, and write a manual that explains what each class does. or…… - Register four (!) new styles that are located in the block options: "Fill Wide", "Fill Full", "Outline Wide", and "Outline Full".
Neither option is elegant enough. (By the way, what exactly is "Fill Full"? What a unfortunate long word!)
I haven't listed two other options:
- Filter button blocks and add custom width controls to them
- Building custom blocks from scratch
These are obviously too arduous for such a simple task.
Enter a block variant! By adding only two variants, "Full" and "Wide", we can keep it simple and concise:
<code>wp.blocks.registerBlockVariation( 'core/buttons', [ { name: 'wide', title: 'Wide Buttons', attributes: { className: 'is-wide' }, }, { name: 'full', title: 'Full Buttons', attributes: { className: 'is-full' }, } ] );</code>
This is the same as adding a custom class to a button block, but it is a neat and elegant way to add it directly to the post from the block inserter:
Life is beautiful, everyone is happy again! So what have we learned from this example?
- It shows that block variants are not intended to replace block styles. In fact, even if the variants simply add a class to the block, they work well together.
- It demonstrates how to register multiple variants in a single declaration.
Use case: Repeat column layout
Suppose you are a designer and have a portfolio website with case studies. Each case study has an introduction section that contains the project name, client information, and a description of your role in the project. It might look like this:
The problem is that this part of building the layout is cumbersome every time you create a new portfolio case study – especially since the titles of “Customer” and “My Role” never change. You only need to edit the main title and two paragraphs of text.
Using block variants, you can create a variant of the core "Columns" block called "Project Intro", which will have defined columns and internal blocks. This example is a little more complex than the first one, so we will build it step by step.
Let's start with registering the variant:
<code>wp.blocks.registerBlockVariation( 'core/columns', { name: 'project-intro', title: 'Project Intro', scope: ['inserter'], innerBlocks: [ ['core/column'], ['core/column'], ['core/column'], ], } );</code>
We take this example a step further than the first one, so why not add a custom portfolio icon from the Dashicons library, which is built directly into WordPress? We use icon
attribute to do this.
<code>wp.blocks.registerBlockVariation( 'core/columns', { name: 'project-intro', title: 'Project Intro', icon: 'portfolio', scope: ['inserter'], innerBlocks: [ ['core/column'], ['core/column'], ['core/column'], ], } );</code>
This will make the block available in the block menu with our icon:
The next important thing happens where we add internal blocks:
<code>wp.blocks.registerBlockVariation( 'core/columns', { name: 'project-intro', title: 'Project Intro', icon: 'portfolio', scope: ['inserter'], innerBlocks: [ ['core/column'], ['core/column'], ['core/column'], ], } );</code>
But this will only give us three empty columns. Let's add the starting content and internal blocks to them. We can use the same pattern as declaring block templates in the InnerBlocks component. We can add an object with block attributes as the second element in the array describing blocks, and an internal block array as the third element.
The first column will look like this:
<code>['core/column', {}, [ ['core/heading', { level: 2, placeholder: 'Project Title'} ], ]]</code>
...The complete block variant is as follows:
<code>wp.blocks.registerBlockVariation ( 'core/columns', { name: 'project-intro', title: 'Project Intro', icon: 'portfolio', scope: ['inserter'], innerBlocks: [ ['core/column', {}, [ ['core/heading', { level: 2, placeholder: 'Project Title' }], ]], ['core/column', {}, [ ['core/heading', { level: 3, content: 'Client' }], ['core/paragraph', { placeholder: 'Enter client info' }], ]], ['core/column', {}, [ ['core/heading', { level: 3, content: 'My Role' }], ['core/paragraph', { placeholder: 'Describe your role' }], ]], ], } );</code>
Cool, now we can insert the entire section with just one click. Well, it takes a few clicks, but it's still faster than not using the variant.
So what have we learned from this example?
- And demonstrate how to use internal blocks in variants
- It shows how to define custom icons for variants
Use case: Four column layout
You already know that columns are a default block type and there are several different types of column options. The four-column layout is not one of them, so we can build it. But this will also introduce a new concept: the scope of block variants.
Some core blocks, such as "Columns", have provided ready-made variants. You can select one of them after inserting a block on the page:
Suppose you use a four-column layout on your website often, just as often as you use a two-column layout. This is unfortunate because there are no shortcut buttons to create a four-column layout. Creating it is a bit annoying, because after inserting a block, an extra click is required to reach the column control:
So, what can you do to improve this workflow? Yes, you can add a block variant that will create a four-column layout. The only difference this time compared to the previous example is that including this variant in the block placeholder, along with all other column layouts, makes more sense.
This is exactly what scope
option does. If you set it to ['block']
, the variant will not appear in the block inserter, but will appear in the variant after the block is inserted.
<code>wp.blocks.registerBlockVariation( 'core/columns', { name: 'four-columns', title: 'Four columns; equal split', icon:<svg ...=""></svg></code> , scope: ['block'], // Highlight innerBlocks: [ ['core/column'], ['core/column'], ['core/column'], ['core/column'], ], } );
Isn't it very sweet? !
I've omitted the full SVG code for the icon, but it's also available if you need it.
To summarize the scope: If not declared, the variant will appear in the block inserter and the block placeholder—especially for blocks that support block range variants.
If we remove the scope
parameter from the example above, the variant will appear in the inserter as follows:
So what have we learned from this example?
- It explains the difference between block and inserter range in variants.
- We learned how to use SVG as a variant icon.
Summarize
As you can see, block variants are very powerful for building a lot of things, from buttons for different variants to full page layouts.
I want to end this article with a quick review of the custom APIs for different blocks and when to use them:
- If you need to change the appearance of a block and adding a CSS class is enough, use the block style .
- If you need to specify the default properties of a block and/or add internal blocks to it, use a block variant .
- If that's not enough and you need to change the block's markup, you may be considering filtering the block or creating a new block from scratch.
If you have the chance to use block variants, please let me know what you think in the comments!
resource
- Make WordPress Articles
- GitHub Pull Request #20068
The above is the detailed content of How to Use Block Variations in WordPress. For more information, please follow other related articles on the PHP Chinese website!

If you've ever had to display an interactive animation during a live talk or a class, then you may know that it's not always easy to interact with your slides

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools