我们能为您提供什么帮助?

搜索我们的指南和教程,或浏览下方分类。

WordPress How to register block variations with PHP

356 次浏览 Markdown

Block variations hook and callback

Technically, WordPress 6.5 doesn’t create a standard set of API functions to use for registering variations. But it does add a new filter hook named get_block_type_variations, which lets you inject custom variations from either a plugin or theme.

Take a look at the get_block_type_variations filter hook:

apply_filters(
	'get_block_type_variations',
	array $variations,
	WP_Block_Type $block_type
);

As shown, the hook can pass up to two parameters to any filters that are applied to it:

  • $variations: An array of registered variations for the specific block.
  • $block_type: An instance of the WP_Block_Type class, representing a registered block type.

When defining a filter for the hook, you will almost always need both of these parameters. So be sure to set the $accepted_args parameter to 2 when calling the add_filter() function.

The following is an example of a fictional filter on get_block_type_variations to familiarize you with how it should be formatted:

add_filter( 'get_block_type_variations', 'themeslug_block_type_variations', 10, 2 );

function themeslug_block_type_variations( $variations, $block_type ) {

	if ( 'namespace/block-a' === $block_type->name ) {
		// Add variations to the `$variations` array.
	} elseif ( 'namespace/block-b' === $block_type->name ) {
		// Add more variations to the `$variations` array.
	}

	return $variations;
}

It’s always necessary to run an if conditional check to determine whether the block is the one you want to define a variation for. You can use the name property of the $block parameter to do this.

Your filter function can also add multiple variations for a single block or define variations for multiple blocks by appending them to the $variations parameter.

Building a custom variation

Now it’s time to get to the fun part: registering a custom block variation!

For this example, let’s use PHP to recreate a JavaScript-based example from the Variations API Block Editor Handbook documentation. The variation makes a single attribute change: it moves the media section from the Media & Text block to the right.

When inserted into the Block Editor, the variation will look like this:

 

Post By WordPress

这对您有帮助吗?

感谢您的反馈!

仍需帮助?

如果上述内容未能解答您的问题,我们的支持团队全天候为您服务。