使用Webpack构建在插件中注册多个自定义gutenberg块

时间:2019-05-08 17:12:07

标签: wordpress wordpress-gutenberg gutenberg-blocks

我正在开发一个捆绑了多个自定义gutenberg块的插件,并且正在使用@ wordpress / scripts npm模块与webpack一起构建。到目前为止效果很好,但是在编辑器中工作时检查控制台给我有关已注册块的错误。当前,我有5个块,每个块有4个错误,因此,我假设在插件PHP中的每个注册函数调用中,所有块均尝试再次注册。每个块都有自己的src-js文件,所有文件都捆绑到一个build-js中。此外,每个块在PHP中都有自己的带有add_action的注册函数,但plugins_url始终是相同的build-js。我相信这是我的PHP文件如何处理注册的问题,但是老实说,我坚持解决该问题。我仍在努力应对区块带来的所有变化。也许有人已经做到了,可以指出正确的方向吗?

带有2个块的PHP代码示例

<?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' );

1 个答案:

答案 0 :(得分:1)

使用wp_register_script()和所有依赖项定义build-JS,然后使用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' );

除了editor_script之外,register_block_type()还接受style和editor_style作为CSS文件的参数。如果它是动态块,则还可以使用render_callback传递渲染函数。

相关问题