Skip to content

Buttons

The core/buttons block built into WordPress is already a powerful block that is useful for handling buttons across a site. This is what we use instead of building a custom block to handle buttons on our sites. However, we do want the button to match the styling for our theme for a site. To accomplish this, we can register styles to the core/buttons block that match our theme.

First, we register the styles that we want to use in our editor.js file.

wp.domReady(() => {
    wp.blocks.registerBlockStyle("core/button", {
        name: "btn-1",
        label: "Button 1",
    });
    wp.blocks.registerBlockStyle("core/button", {
        name: "btn-2",
        label: "Button 2",
    });
});

You can register as many styles as needed for the design. Most designs call for at least two.

It is useful to change the label to something brief but descriptive for useability (i.e. if there is a black styled button and a blue styled button for a site you may register them with labels 'Black Button' and 'Blue Button').

Next, we will define the styling of those block styles in our components.css file.

/* Button Styles */
/* It's useful to have these classes separated out so they can also be @apply-ed if needed but if they are going to be @apply-ed outside of the components.css file then they also need to be added to tailwind.config.js */
    .button-1 {
        @apply font-normal border-white hover:border-secondary border-solid border-[1px] transition rounded-[10px] py-1 px-8 !text-lg text-white hover:text-black no-underline bg-secondary duration-200 hover:bg-white flex;
    }

    .button-2 {
        @apply font-normal border-black hover:border-white border-solid border-[1px] transition rounded-[10px] py-1 px-8 !text-lg text-black hover:text-white hover:bg-black no-underline bg-white duration-200 flex;
    }

/* This top one defines the default style so that when a user drops the button it is automatically styled to match the theme without having to choose a style. The user can still choose a style if they want to pick an alternative appearance that still matches the theme */
    .wp-block-button .wp-block-button__link {
        @apply button-1;
    }

    .wp-block-button.is-style-btn-1 .wp-block-button__link {
        @apply button-1;
    }
    .wp-block-button.is-style-btn-2 .wp-block-button__link {
        @apply button-2;
    }