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. With the new register_block_style PHP function in WordPress version 5.3, you can achieve the same result by adding custom block styles with PHP, 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 basic gallery block style as in our previous examples.

Open your child themes functions.php file.

To register your block style, copy the following code and add it to the file:

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

First, we are including the block name: Core/gallery.

Then we are adding three arguments: Name, label, and inline style.

  • Name is the CSS class that will be added to the block to identify it.
  • Label is the name that will be visible in the block’s style selector in the editor.
  • Inline_Style is the CSS code that will be applied to the block.

Remember to change the slug (the prefix), before you save your file.

The style should now be available in the editor:

A gallery block style with hidden captions.

By adding custom block styles with PHP, we can reduce the number of files that we need to include, since register_block_style() already includes the JavaScript and CSS for us.

As the name suggest, the CSS is added inline. Specifically, it is added to the wp-block-library stylesheet.

If you need to dequeue the wp-block-library stylesheet, you need to add the CSS to a different stylesheet that is loaded on the front.

Recommended reading