Categories
Beginners Quick guide

Adding custom block styles with PHP

Earlier this year I wrote two articles about how to add custom block styles with JavaScript and CSS files, and how to enqueue those files for the styles to work both in the editor and in the front.

With the new register_block_style PHP function that is available from WordPress version 5.3, you can achieve the same result with a lot less code and fever steps.

First, make sure that you have created a child theme. Do not edit the parent theme directly, or you will lose your changes when the theme is updated.

We will be using the same gallery style as in our previous examples.

Open your child themes functions.php file.

Copy the following code and add it to the file:

register_block_style(
    'core/gallery',
    array(
        'name'  => 'slug-hide-caption',
        'label' => __( 'Hide caption', 'text-domain' ),
        'inline_style' => '.is-style-slug-hide-caption figcaption { display: none; }',
    )
);

Remember to save your file.

The style should now be available in the editor, since register_block_style already includes the JavaScript and CSS for us.

Recommended reading