To be fair, this works pretty well. But it does mean you have to create the .js file, enqueue it properly and create the Css to handle this style variation.
As of WordPress 5.3 we can achieve the same thing with a simple Php function call.
Register Gutenberg block styles with Php
To register custom block styles we can now use the register_block_style Php function like shown below.
With the code above we add an action to the after_setup_theme hook, and register the register_uppercase_heading callback function.
Inside the register_uppercase_heading function we use the new register_block_style function and pass it the following parameters.
- Block: The block for which we want to register the style.
- Attributes: An array of attributes.
- Attributes > Name: The name of the style. This will be used to create the css class.
- Attributes > Label: The label that will be shown in the Editor.
- Attributes > Inline_style: The inline css rules for the style.
The most important thing to notice here is that the Name attribute will be used to create a css class for the block. In the example above we give the Name attribute a value of uppercase-heading this will result in a class name of is-style-uppercase-heading on the heading block which we use in the inline_style attribute.
The code above will enable the styles tab on the sidebar for the heading block like shown in the image below:
Block styles with a stylesheet handle
Instead of passing a inline style to the register_block_style function we can also pass the handle of any previously registered stylesheet like shown below.
In this example we first register a new stylesheet, using the wp_register_style function, with a “block-style-uppercase-heading” handle. We then replace the inline_style attribute with a style_handle attribute and give it the same “block-style-uppercase-heading” stylesheet handle.
You can now create the Css file we registered called block-style-uppercase-heading.css in the root of your theme with the following content:
The stylesheet will get enqueued when it is needed automatically.
Removing server-side block styles
To remove block styles you can use the new unregister_block_style Php function like shown below.
This function excepts the following parameters:
- Block: The name of the block you want to remove a style for.
- Name: The name of the style you want to remove.
If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.
Thanks for reading