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

WordPress Gutenberg核心图片块添加data-source属性时验证失败求助

解决Gutenberg核心图片块添加data-source属性的块验证失败问题

问题根源

  1. 脚本注册错误:add_sction是拼写错误(应为add_action),且wp_enqueue_script()缺少必要参数,导致自定义逻辑未正确加载。
  2. 虚拟DOM修改方式不安全:直接修改extraProps.children.props依赖固定DOM结构,一旦Gutenberg更新块结构,就会导致保存内容与编辑器渲染内容不一致,触发验证失败。
  3. 属性合并方式有风险:使用Object.assign合并属性时,若原有settings.attributes是不可变对象,可能无法正确添加新属性。

修正后的完整代码

1. 正确注册编辑器脚本(在主题functions.php中添加)

function enqueue_sample_plugin_editor_assets() {
    wp_enqueue_script(
        'sample-plugin-editor-script',
        get_template_directory_uri() . '/js/sample-plugin-editor.js', // 替换为你的脚本实际路径
        array( 'wp-blocks', 'wp-element', 'wp-hooks' ),
        filemtime( get_template_directory() . '/js/sample-plugin-editor.js' ),
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'enqueue_sample_plugin_editor_assets' );

注意:确保脚本文件路径正确,依赖项包含wp-blocks、wp-element、wp-hooks这些Gutenberg核心库。

2. 编辑器脚本(sample-plugin-editor.js内容)

// 注册自定义属性
wp.hooks.addFilter(
    'blocks.registerBlockType',
    'sample-plugin/plugin/attribute/data-source',
    (settings, name) => {
        if (name !== 'core/image') {
            return settings;
        }

        // 用扩展运算符安全合并属性,避免覆盖原有引用
        return {
            ...settings,
            attributes: {
                ...settings.attributes,
                'dataSource': { // 驼峰命名符合JS规范,映射到HTML的data-source属性
                    type: 'string',
                    source: 'attribute',
                    selector: 'img',
                    attribute: 'data-source',
                    default: '',
                },
            },
        };
    }
);

// 修改保存内容的属性
wp.hooks.addFilter(
    'blocks.getSaveContent.extraProps',
    'sample-plugin/plugin/add-data-source',
    (extraProps, blockType, attributes) => {
        if (blockType.name !== 'core/image') {
            return extraProps;
        }

        // 直接检查并修改img的props,适配Gutenberg块结构
        if (extraProps.children && extraProps.children.type === 'img') {
            extraProps.children.props = {
                ...extraProps.children.props,
                'data-source': attributes.dataSource || '',
            };
        }

        return extraProps;
    }
);

关键修正点说明

  • 属性命名规范:用驼峰dataSource作为编辑器内部属性名,映射到HTML的data-source属性,避免连字符在JS对象属性中的潜在问题。
  • 安全对象合并:使用扩展运算符...替代Object.assign,确保不修改原对象引用,避免意外影响其他块逻辑。
  • DOM结构兼容:直接检查extraProps.children是否为img元素,而非依赖多层嵌套的固定结构,适配Gutenberg可能的版本更新。
  • 脚本加载修复:修正add_action拼写错误,补充wp_enqueue_script的必要参数,确保脚本在编辑器环境正确加载。

验证方法

  1. 替换原有代码为上述修正后的代码。
  2. 进入编辑器添加核心图片块,设置data-source属性(若需要可视化设置,可额外通过editor.BlockEdit过滤器添加侧边栏输入框)。
  3. 保存文章后刷新编辑器,若不再出现块验证失败提示,说明问题解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:27:11