Day 11: Creating Block Variations in Gutenberg

·

·

Introduction

Welcome to Day 11 of the Gutenberg development series! In today’s article, we’ll explore block variations, a feature that allows you to create multiple versions or styles of a single block. By offering different variations, you can simplify the editor experience and give users more flexibility in choosing the right layout or style for their content.

For example, you can create a single Button block and offer variations like Primary Button, Secondary Button, or Outline Button.

In this guide, we’ll walk through how to define block variations, add custom styles, and manage the variations effectively.

What are Block Variations in Gutenberg?

A block variation is essentially a different version of a block with pre-defined attributes. This enables users to select from multiple styles or settings without having to modify the block manually every time they add it. Variations can have:

  • Different styles or colors.
  • Custom settings (like size, layout).
  • Unique default content.

Step 1: Creating Basic Block Variations

Let’s start by creating block variations for the core/button block. We’ll define three variations: Primary Button, Secondary Button, and Outline Button.

  1. Create a JavaScript File for Variations

Create a JavaScript file in your theme or plugin folder to define the block variations. For example, you can name it button-variations.js.

// blocks/button-variations.js
import { registerBlockVariation } from '@wordpress/blocks';

// Define variations for the core/button block
const buttonVariations = [
    {
        name: 'primary-button',
        title: 'Primary Button',
        description: 'A bold, standout button.',
        isDefault: true,
        attributes: { backgroundColor: 'blue', textColor: 'white' },
        innerBlocks: [['core/paragraph', { placeholder: 'Click me!' }]],
        icon: 'button',
    },
    {
        name: 'secondary-button',
        title: 'Secondary Button',
        description: 'A subtle button for secondary actions.',
        attributes: { backgroundColor: 'gray', textColor: 'white' },
        icon: 'button',
    },
    {
        name: 'outline-button',
        title: 'Outline Button',
        description: 'A button with an outline style.',
        attributes: { backgroundColor: 'transparent', textColor: 'blue', className: 'outline-button' },
        icon: 'button',
    }
];

// Register the variations with the core/button block
buttonVariations.forEach((variation) => {
    registerBlockVariation('core/button', variation);
});

Explanation:

  • registerBlockVariation: This function registers a new variation for an existing block. Here, we add variations for the core/button block.
  • name: A unique identifier for the variation.
  • title: Display name shown to users in the block inserter.
  • attributes: Sets the default attributes for each variation, such as background color, text color, or custom classes.
  • innerBlocks: Optional. If needed, you can define nested blocks for the variation (e.g., pre-filled text inside a button).
  • icon: Icon for the variation, making it visually identifiable in the block inserter.

Step 2: Enqueuing the Script

To make the block variations available in the Gutenberg editor, enqueue the script in your theme’s functions.php file.

function my_theme_enqueue_variation_script() {
    wp_enqueue_script(
        'my-theme-button-variations',
        get_template_directory_uri() . '/blocks/button-variations.js',
        array( 'wp-blocks', 'wp-editor' ),
        filemtime( get_template_directory() . '/blocks/button-variations.js' ),
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'my_theme_enqueue_variation_script' );

This code ensures that the variations are loaded in the block editor.

Step 3: Styling Block Variations

You might want to apply custom styles for each variation. To do this, add some CSS to your theme’s stylesheet (e.g., style.css).

/* Primary Button */
.wp-block-button.is-style-primary-button .wp-block-button__link {
    background-color: blue;
    color: white;
}

/* Secondary Button */
.wp-block-button.is-style-secondary-button .wp-block-button__link {
    background-color: gray;
    color: white;
}

/* Outline Button */
.wp-block-button.is-style-outline-button .wp-block-button__link {
    background-color: transparent;
    color: blue;
    border: 2px solid blue;
}

Explanation:

  • .wp-block-button.is-style-{variation-name}: This targets the button variations and applies custom styles to each.
  • You can adjust properties like background-color, color, border, etc., based on your design needs.

Step 4: Using Block Variations in the Editor

With your block variations registered and styled, it’s time to use them in the Gutenberg editor.

  1. Open the Block Editor:
    • Go to any post or page in WordPress and open the Block Editor.
  2. Add a Button Block:
    • Click the “+” button to insert a block.
    • Search for Button. You’ll notice the different variations (Primary, Secondary, Outline) are now available.
  3. Choose a Variation:
    • Select the desired button variation, and it will be added to your content with the default style and settings applied.
  4. Customize as Needed:
    • You can further customize the button text, URL, and additional attributes as you would with a regular button block.

Step 5: Managing and Updating Variations

Block variations are designed to enhance user flexibility. If you need to update or change a variation:

  1. Modify the JavaScript: Update the attributes, settings, or description in button-variations.js.
  2. Rebuild and Test: Make sure to rebuild your development environment (if necessary) and test the variations in the editor.

Best Practices for Creating Block Variations

  1. Keep it Simple: Provide variations for the most commonly used styles or settings, but avoid creating too many variations that may confuse users.
  2. Use Meaningful Names: Use descriptive titles and names so users can easily understand the purpose of each variation.
  3. Leverage Default Attributes: Set sensible defaults for each variation so that users can quickly add the block without making further adjustments.

Conclusion: Enhancing Flexibility with Block Variations

Block variations are a powerful way to add customization options for your users while keeping the block development process simple and efficient. By creating multiple styles and settings for a single block, you can offer diverse options for content creation without overwhelming the editor.

In this article, you’ve learned how to:

  • Register and define block variations for an existing block.
  • Enqueue scripts to make the variations available in the editor.
  • Style variations using CSS for custom appearance.
  • Manage and update variations as needed.

In Day 12, we’ll explore how to build custom block categories and collections to organize your custom blocks more effectively in the WordPress editor.


Leave a Reply

Your email address will not be published. Required fields are marked *