Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering multiple custom gutenberg blocks in a plugin with webpack build

I am working on a plugin that bundles multiple custom gutenberg blocks and I am using the @wordpress/scripts npm module to build with webpack. Works great so far, but checking the console when working in the editor gives me errors about blocks being registered already. Currently I have 5 blocks and 4 errors for each, so I assume on each register function call in my plugin PHP all blocks try to register again. Each block has its own src-js file and all get bundled into a single build-js. Furthermore each block has its own register function with add_action in the PHP but the plugins_url is always the same build-js. I believe it's a problem with how my PHP file is handling the registration but I am honestly stuck on how to solve this. I am still struggling with all the changes developing with blocks brings. Maybe anybody has done this already and can point me in the right direction?

Example PHP code with 2 blocks

<?php
/*
Plugin Name: My Blocks Plugin
*/

/* Block 1 */

function register_my_block_1() {
    wp_register_script(
        'foo-my-block-1',
        plugins_url( 'build/index.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-editor' )
    );

    register_block_type( 'foo/my-block-1', array(
        'editor_script' => 'foo-my-block-1',
    ) );

}
add_action( 'init', 'register_my_block_1' );

/* Block 2 */

function register_my_block_2() {
    wp_register_script(
        'foo-my-block-2',
        plugins_url( 'build/index.js', __FILE__ ),
        array( 'wp-blocks', 'wp-i18n' )
    );

    register_block_type( 'foo/my-block-2', array(
        'editor_script' => 'foo-my-block-2',
    ) );

}
add_action( 'init', 'register_my_block_2' );
like image 998
Vortac Avatar asked Mar 05 '23 01:03

Vortac


1 Answers

It should be enough to define the build-JS with wp_register_script() and all dependencies and then register each block with register_block_type():

function plugin_slug_register_blocks() {

    // Register build.js
    wp_register_script(
      'plugin-slug-blocks',
        plugins_url( 'build.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element', 'wp-data' )
    );

    // Register Block 1
    register_block_type( 'plugin-slug/block-name-1', array(
       'editor_script' => 'plugin-slug-blocks',
    ) );

    // Register Block 2
    register_block_type( 'plugin-slug/block-name-2', array(
        'editor_script' => 'plugin-slug-blocks',
    ) );
}
add_action( 'init', 'plugin_slug_register_blocks' );

Besides editor_script, register_block_type() also accepts style and editor_style as arguments for the CSS files. If it is a dynamic block, you can also pass a render function with render_callback.

like image 128
Thomas Weichselbaumer Avatar answered Apr 28 '23 10:04

Thomas Weichselbaumer