WordPress / developer-blog-content

In this GitHub space, WordPress team coordinate content to be published on the Developer Blog. Discussion and montly meetings (first Thu) in WP Slack #core-dev-blog
36 stars 2 forks source link

How to register block variations with PHP in WP 6.5 #233

Closed justintadlock closed 3 months ago

justintadlock commented 3 months ago

Discussed in https://github.com/WordPress/developer-blog-content/discussions/228

WordPress 6.5 is shipping with a new get_block_type_variations filter hook: https://github.com/WordPress/wordpress-develop/blob/4ba0963a1f61d062d7345e429c823f3eb5ab5f78/src/wp-includes/class-wp-block-type.php#L608-L616

This essentially works as a PHP-based method of registering custom block variations. This would be a lightweight tutorial for anyone who wants to pick it up and showcase a new WP 6.5 feature. Of course, I'm always happy to take this one on myself too.

Some possible limitations I've seen in my early testing so far:

Example

Here's an example variation on the Spacer block that's specific to my theme, but it's just a PoC:

add_filter('get_block_type_variations', function($variations, $block_type) {

    if ('core/spacer' === $block_type->name) {
        $variations[] = [
            'name'       =>      'x3p0/theme-spacer',
            'title'      =>      __('Spacer', 'x3p0-ideas'),
            'keywords'   =>   [ 'space', 'spacer', 'spacing' ],
            'isDefault'  => true,
            'isActive'   => [ 'height' ],
            'attributes' => [
                'height' => 'var:preset|spacing|plus-8'
            ]
        ];
    }

    return $variations;
});
justintadlock commented 3 months ago

I'll be drafting this here: https://docs.google.com/document/d/1UYFcL_QFcj5fXNWDN5DVGBJJ4R8BIDSplIWYhQ2hGd8/edit?usp=sharing

justintadlock commented 3 months ago

Props to @ndiego for the first review.

eidolonnight commented 3 months ago

This looks good to me as well. Nice work @justintadlock .

justintadlock commented 3 months ago

Thanks, @eidolonnight.

justintadlock commented 3 months ago

Social Copy:

WordPress 6.5 has a new hook for registering block variations with PHP. No JavaScript required. Learn more on the Developer Blog:

https://developer.wordpress.org/news/2024/03/14/how-to-register-block-variations-with-php/

bph commented 2 months ago

scheduled for April 23 on Social.