Learn in this tutorial how to create variations for the default gallery block with a little bit of code.
You know I’m a big fan of taking advantage of the block editor, especially by extending its native capabilities.
In a previous tutorial I told you that block variations allow you to customize the structure and add/remove/modify inner blocks.
But besides creating new variations you can also create modifications that affect the default version of a block.
With an example you will understand it better. 😉
The gallery block crops the images by default, but you can create a variation so that it doesn’t do it and thus avoid having to change that setting every time you add a new gallery block.
Here’s how to do it.
Steps to create a variation of the gallery block in WordPress
1. Register a new block variation
The first thing you need to do is to register the new variations.
To do this create a file called block-variations.js inside the /assets/js/ folder of your theme (if it doesn’t exist you can create it) with one of the following codes:
In the above 3 snippets the variation contains the following fields:
/gallery: the gallery block for which you are creating the variation.
trueyou indicate that it is a default variation.
attributes: the block attributes.
In this case, neither
label are necessary since you are not creating a new variation, but modifying the default one.
In the attributes you indicate, depending on the example:
cropsthe image, if
falseit does not.
linkTo: you indicate the destination of the image
sizeSlug: specify the size of the image
You can see the determined attributes that each block has in the official documentation.
In the 3 examples you get the following:
- That the images are not cropped.
- That the images are linked to the media file (ideal if you use a lightbox plugin and want to make sure it works in galleries).
- The two above, plus that the default size of the image is medium and that the image opens in a new page.
You can see that for all practical purposes the new variation you have created replaces the native block with the new settings.
2. Enqueue the new styles
Once you have the file where you have registered the styles, you have to enqueue them to the theme. To do this, add the following snippet to the end of functions.php:
As you can see, this is not a very complicated process and can give you a lot to play with.
And this is a simple example that can inspire you to create your own default variations of blocks.
The WordPress block editor allows for a lot of customization possibilities. If you want to get the most out of it, customizing the settings of a block by creating a variation of the default version is a good way to do it and now you know how.
If you have any question, please leave it in the comments. And if you want to give me a suggestion for future snippets, please send it through the contact form.
Benefits of being a subscriber. 🙂