Skip to main content

WordPress - Creating Custom Styles

·226 words
icysamon
Author
icysamon
Electronics & Creator
Table of Contents

WordPress block themes are very convenient because they allow you to edit websites intuitively, but they have the disadvantage of offering fewer customization options out of the box.

In this case, you can use your theme’s functions.php file to add custom styles like the ones below.

Code
#

function themeslug_register_block_styles() {
    register_block_style( 'core/group', array(
        'name' => 'default',
        'label' => __( 'Default', 'themeslug' ),
        'is_default' => true,
        'inline_style' => '.wp-block-group.is-style-default {}' 
    ) );
    
    register_block_style( 'core/group', array(
        'name' => 'widget',
        'label' => __( 'Widget', 'themeslug' ),
        'inline_style' => '.wp-block-group.is-style-widget {
            background-color: #faf0e6;
            border-radius: 25px;
        }' 
    ) );
}
add_action( 'init', 'themeslug_register_block_styles' );

Code Breakdown
#

First, create a function named themeslug_register_block_styles(). You can use a different name if you prefer.

Then, set the default style.

register_block_style( 'core/group', array(
    'name' => 'default',
    'label' => __( 'Default', 'themeslug' ),
    'is_default' => true,
    'inline_style' => '.wp-block-group.is-style-default {}' 
) );

Next, create the custom style.

register_block_style( 'core/group', array(
    'name' => 'widget',
    'label' => __( 'Widget', 'themeslug' ),
    'inline_style' => '.wp-block-group.is-style-widget {
        background-color: #faf0e6;
        border-radius: 25px;
    }' 
) );

name is the name of your custom style, and inline_style is where you set the custom CSS.

Since we are customizing the Group block here, the base CSS class is .wp-block-group.

Because the style name is widget, we append .is-style-widget to it.

Finally, execute the function you created using add_action().

add_action( 'init', 'themeslug_register_block_styles' );