Learn in this tutorial how to create custom styles for WordPress gallery block and add them to a theme.
One of the features of WordPress editor blocks is that they can have different styles
For example, the image block shows two options:
In a previous tutorial I explained how you can easily create your own block styles.
But WordPress 5.9 has introduced quite a few new features, among them, the gallery block has been redesigned and is now an image container.
This allows us to modify the images individually and opens up new design possibilities.
In this tutorial you are going to see how to create a custom block style for the gallery block and have it available in your child theme.
Steps to create custom styles for gallery block in WordPress
1. Register the new styles
The first thing you need to do is to register the new styles.
To do this create a file called gallery-block-styles.js inside the /js/ folder with the following code :
Each style consists of 4 elements:
- core/gallery -> the gallery block to which we are going to add the new styles
- name -> internal name that will also be given by the CSS class.
- label -> label used for the name displayed in the editor.
- isDefault -> whether you want it to be the default style or not.
With the above example you register a new style for the gallery block:
- 3×3 gallery with rounded borders
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:
3. CSS styling
When registering new block styles you have used nomenclatures that translate into CSS classes. Specifically
Now you have to use this class to give the layout you want and add it to both the frontend and editor stylesheet.
In the case of Genesis Sample you must add it at the end of the file:
Watch out! If you only include it at the front you will not be able to preview the styles in the editor.
This is a simple example to inspire you to create your own block styles
If you notice, this way of doing it has the limitation that, for the gallery to look with rounded edges it has to be 3×3 photos. If you want it to be 4×4 you would have to create a new custom style and so on.
But in this other tutorial you will learn another strategy to achieve the same regardless of the dimensions of the gallery.
So you can choose the one that works best for you. 😉
The WordPress block editor allows a lot of customization possibilities. With the arrival of WordPress 5.9 you can get more out of it by creating your own custom gallery styles. And now you know how to do it.
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. 🙂