星期三 , 22 1 月 2025

创建只添加一个div的区块

// Save this as container-block.js in your theme or plugin directory

( function( blocks, element, blockEditor ) {
    var el = element.createElement;
    var InnerBlocks = blockEditor.InnerBlocks;

    blocks.registerBlockType( 'custom/container-block', {
        title: 'Single Div Container',
        icon: 'editor-contract',
        category: 'layout',
        attributes: {
            className: {
                type: 'string',
            },
        },

        edit: function( props ) {
            return el(
                'div',
                { className: props.attributes.className },
                el( InnerBlocks )
            );
        },

        save: function( props ) {
            return el(
                'div',
                { className: props.attributes.className },
                el( InnerBlocks.Content )
            );
        },
    } );
} )( window.wp.blocks, window.wp.element, window.wp.blockEditor );

将上面的js代码复制粘贴到主题根目录下面的blocks文件夹里的container-block.js文件,如果没有请新建,然后在functions.php 通过下面代码引入,创建新区块;

function enqueue_container_block_script() {
    wp_enqueue_script(
        'container-block-script',
        get_template_directory_uri() . '/path/to/container-block.js',
        array( 'wp-blocks', 'wp-element', 'wp-block-editor' ),
        filemtime( get_template_directory() . '/path/to/container-block.js' )
    );
}
add_action( 'enqueue_block_editor_assets', 'enqueue_container_block_script' );