admin管理员组

文章数量:1122832

Currently, both register_block_style and register_block_type exist in PHP as alternative to the same functions in javascript registerBlockStyle and registerBlockType. However, it seems that register_block_variation does not exist. Is there possibility to register core block variation from PHP?

Currently, both register_block_style and register_block_type exist in PHP as alternative to the same functions in javascript registerBlockStyle and registerBlockType. However, it seems that register_block_variation does not exist. Is there possibility to register core block variation from PHP?

Share Improve this question asked Mar 26, 2022 at 19:21 LovorLovor 9869 silver badges16 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

As of January 2023, it seems that this function remains unavailable in PHP. The only issue where I find any mention to it in Gutenberg repo is this one: https://github.com/WordPress/gutenberg/issues/24994

I've opened an issue requesting it, let's see if they can handle it :) https://github.com/WordPress/gutenberg/issues/47170

EDIT: since WP 6.5.0 there is a filter get_block_type_variations for adding/changing block variations, including extending variations on core blocks. See: https://developer.wordpress.org/news/2024/03/14/how-to-register-block-variations-with-php/


I found a workaround. Following snippet registers variant of post-excerpt block which will have only three lines of text. It does so by intercepting metadata from block.json and injecting new.

<?php
function extended_query_excerpt_block_args($args) {
    $args['render_callback'] = 'render_block_core_post_excerpt';
    $args['attributes']['variantType'] = [
        'type' => 'string'
    ];
    $args['variations'] = [
        [
            'name' => 'three-lines-excerpt',
            'title' => 'Three lines excerpt',
            'attributes' => [
                'variantType' => 'three-lines-excerpt'
            ],
        ]
    ];
    return $args;
}

function register_variation($args, $block_type) {
    switch ($block_type) {
        case 'core/post-excerpt':
            $args = extended_query_excerpt_block_args($args);
            break;
    }
    return $args;
}

add_filter( 'register_block_type_args', 'register_variation', 10, 2 );

本文标签: block variations registration in PHP