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

Categories
Beginners Quick guide

How to add a new default block style

When you add a new block style, you can also make it the default style in the editor.

Revisiting our gallery block where we hid the captions, we only need to add one new line: isDefault: true.

Our example codes would then look like this:

JavaScript:

wp.blocks.registerBlockStyle('core/gallery', {
	name: 'slug-hide-caption',
	label: wp.i18n.__('Hide captions', 'text-domain'),
        isDefault: true
});

Or, if you added the block style with PHP:

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; }',
        'isdefault' => true,
    )
);

Categories
Beginners Quick guide

What is a custom block style?

A custom block style is a style change that is applied to a WordPress block to make it look different from the default styles.

The difference between a custom block style and a custom block is that the custom style is added to existing blocks, while custom blocks are new blocks. It is usually simpler to create custom styles than entire blocks.

The custom block style can then be selected in the WordPress editor:

An image describing the settings for the gallery block in the WordPress editor. A new block style called Hide captions is available for selection.
Example of a custom style added to a gallery block.

How a custom style is added

You can add block styles with either PHP or JavaScript combined with CSS. The style is used both in the editor and the front.

If you want to know more, you can continue with these two guides: