Welcome to this lesson where we dive into extending registered blocks and create alternate versions of a block’s settings.
With this lesson, you will:
- describe block variations,
- differentiate between block variations and block styles,
- add the JavaScript file to your theme, and
- register a block variation.
What is a block variation?
A block variation is an alternative block you can add to your theme using the block variations API. You would use the attributes already assigned to the block you are creating a variation from.
You wouldn’t require a build process as you can choose to enqueue your custom JavaScript file from functions.php, along with passing through a few dependencies.
You can choose to place your block variation within a plugin or within your theme files.
If you haven’t already had a chance to take a look at the Beginner WordPress developer learning pathway, do check out the module on developing WordPress plugins.
Block variations vs Block styles
What is the difference between block variations and block styles?
The main difference between a block variation and a block style is that a block style applies a CSS class to the block so it can be styled in an alternative way.
Let’s take a look at an example using the Twenty Twenty-Four theme.
They have this block style with asterisks. And you see the CSS class is style asterisks.
This can be applied to headings, however, it’s not a block style available to the paragraph block, just the heading block.
If you click on the insertor and scroll down, you’ll see an example of block variations. This ships with WordPress core and each one of these embeds is a block variation.
To review the entire code, you can take a look on GitHub.
If you’d like to learn more about the difference between block variations and block styles, there’s a great online workshop that you can refer to.
Adding JavaScript
Now let’s add the JavaScript file to your theme.
You can name your JavaScript file block hyphen variations and place it within the JS subfolder under assets.
Register block variations
Now let’s register the block variation.
You could use the functions.php file, open up your PHP, use the enqueue block editor assets action hook and use the WP enqueue script function.
You see here that the block variations.js file is being called along with an array of some dependencies.
add_action( 'enqueue_block_editor_assets', 'themeslug_enqueue_block_variations' );
function themeslug_enqueue_block_variations() {
wp_enqueue_script(
'themeslug-block-variations',
get_theme_file_uri( 'assets/js/block-variations.js' ),
array(
'wp-blocks',
'wp-dom-ready',
'wp-i18n'
),
wp_get_theme()->get( 'Version' ),
true
);
}
Next steps
You can learn more about variations by referring to the block editor handbook, or you can take a look at the theme handbook. And finally, there’s a great blog post available on WordPress.org on their WordPress developer blog.