Easily enhance the block editor with custom block styles.
Update 7 May: Paul reported that the styles were not being included on the front end for him. He’s using the default Twenty Twenty Two theme, a Full Site Editing (FSE) theme. I tried it and a few other FSE themes and they all had the same issue. As a workaround I updated the code to always enqueue the stylesheet when using one of those themes. I’ll investigate if it is a FSE bug.
When you upload an image to the block editor you will see Default and Rounded options in the Styles tab. Well, it is super easy to add your own block styles with PHP.
I recently read a post on Brian Gardner’s website (he’s a co-creator of Genesis framework that I have been using and writing about for years) where he described how to create an inner border block style for images. It was surprisingly easy – register the style with register_block_style() and then add the appropriate CSS.
According to the Styles section of the Block Editor Handbook the style can be registered with PHP, with
With register_block_style() you can include inline CSS that will be added to the markup or you reference the handle of a registered CSS file and it will be automatically enqueued. The latter is perfect for when you want to group the CSS for multiple styles. Furthermore, the CSS file will be automatically enqueued in the editor too!
Although block styles are very useful for simple enhancements, as they are active/not active and do not have options, they are a bit limited. In my ‘Rotated‘ style for the Image block the editor cannot adjust the rotation angle. That aside, the ‘Info‘ and ‘Warning‘ Group block styles that I demonstrate are helpful because they allow for multiple other blocks inside the Group block and all can inherit the appropriate styles (I say ‘can inherit’ because you may need to add CSS to fix the styling of some of the inner blocks).
While you can add styles to any block, I limited my examples to some core blocks.
For the image block (‘core/image’ internal name) I added a ‘Rotated‘ style that simply does a 180 degree rotation. You can see this as the upside down map in the screenshot below.
For the Group block I registered ‘Info‘ and ‘Warning‘ styles. These are to mimic shortcodes that were part of a previous theme on this site. So as not to break the posts when I changed theme, I copied the shortcode function and CSS into a functionality plugin. Now, having discovered custom block styles, I can convert these to Group blocks.
I put the CSS in its own file instead of using inline styles so the code is in two files. Put both of them in the same directory and activate the plugin.