WordPress / gutenberg

The Block Editor project for WordPress and beyond. Plugin is available from the official repository.
https://wordpress.org/gutenberg/
Other
10.58k stars 4.23k forks source link

Docs: Block Variations - Add PHP strategy to register block variations using get_block_type_variations hook #63182

Open juanmaguitar opened 5 months ago

juanmaguitar commented 5 months ago

Block Editor Handbook > Reference Guides > Block API Reference > Variations is lacking a description of how to add variations to a core block from PHP side

An approach that could be recommended from the docs is the use of the get_block_type_variations hook to add any custom variations to blocks on register-time.

This approach is the one used in Gutenberg

gziolo commented 4 months ago

In https://github.com/WordPress/gutenberg/issues/47170, there is proposal for a higher level API in PHP for block variations registration.

retrofox commented 1 week ago

👋 Is the following a proper approach?

<?php

public function add_buttons_variation( $variations, $block_type ) {
  if ( $block_type->name !== 'core/buttons' ) {
    return $variations;
  }

  $variations = array(
    array(
      'name'        => 'my-plugin/buttons',
      'title'       => __( 'My Buttons', 'my-plugin' ),
      'attributes'  => array(
        'displayStyle' => 'icon_and_text',
        'iconStyle'    => 'default',
        'iconClass'    => 'dashicons dashicons-admin-site',
      ),
      'isDefault'   => false,
    ),
  );

  return $variations;
}

add_filter( 'get_block_type_variations', array( $this, 'add_buttons_variation' ), 0, 2 );

I could start to work on this one.

gziolo commented 1 week ago

@retrofox , that looks correct. You can also cross-check with the dev note: https://make.wordpress.org/core/2024/02/29/performance-improvements-for-registering-block-variations-with-callbacks/