You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为WordPress核心Gutenberg块添加parent属性

为WordPress核心Gutenberg块设置允许的父块

要实现核心块(标题、段落、图片、列表)仅能在指定父块内使用、无法出现在顶层,同时保留块模板功能,可以通过Gutenberg提供的blocks.registerBlockType过滤器修改核心块的parent属性,无需直接修改核心代码。以下是具体实现步骤:

1. 注册前端脚本(PHP端)

在主题的functions.php中添加代码,用于加载自定义修改脚本:

function custom_restrict_core_blocks_parent() {
    wp_enqueue_script(
        'core-blocks-parent-restrictor',
        get_template_directory_uri() . '/js/core-blocks-restrict.js',
        array( 'wp-blocks', 'wp-dom-ready', 'wp-edit-post' ),
        wp_get_theme()->get('Version'),
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'custom_restrict_core_blocks_parent' );

2. 修改核心块的父级限制(JS端)

在主题目录下创建js/core-blocks-restrict.js文件,添加以下代码:

wp.domReady( () => {
    // 定义允许的父块(替换为你的自定义容器块名称,比如你的stof/container)
    const allowedParentBlocks = [ 'stof/container' ];

    // 需要限制的核心块列表
    const targetCoreBlocks = [
        'core/heading',
        'core/paragraph',
        'core/image',
        'core/list'
    ];

    targetCoreBlocks.forEach( blockSlug => {
        wp.hooks.addFilter(
            'blocks.registerBlockType',
            `custom/restrict-${blockSlug}-parent`,
            ( blockSettings, blockName ) => {
                // 只修改目标核心块的设置
                if ( blockName !== blockSlug ) return blockSettings;

                // 覆盖parent属性,指定允许的父块
                return {
                    ...blockSettings,
                    parent: allowedParentBlocks
                };
            }
        );
    });
});

关键说明

  • 块名称正确性:核心块的名称是core/heading、core/paragraph这类,不要和自定义块名混淆。
  • 多父块支持:如果需要允许多个父块,直接在allowedParentBlocks数组中添加对应的块slug即可。
  • 块模板兼容性:这种修改不会影响块模板功能——块模板负责指定编辑器允许使用的块,而这里是限制核心块的放置层级,两者逻辑独立,可同时生效。
  • 避免直接修改核心文件:使用过滤器是官方推荐的安全方式,不会因为WordPress更新导致修改失效。

验证效果

进入Gutenberg编辑器后:

  • 尝试在顶层直接添加标题、段落等核心块,编辑器会禁止该操作;
  • 进入你指定的父块(如stof/container)内部,可正常添加这些核心块。

内容的提问来源于stack exchange,提问作者Frizzant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:39:07