【问题标题】:wordpress gutenberg: Block validation failed for `core/image` when adding data attribute (data-id="")wordpress gutenberg:添加数据属性(data-id =“”)时,“核心/图像”的块验证失败
【发布时间】:2020-06-06 13:22:04
【问题描述】:
将 data 属性(使用 Edit as HTML)添加到锚标记时出现 Gutenberg 验证错误,此问题发生在 anchor 时figure 标签内的标签。
当用户添加图像并用链接包装该图像时,onsubmit 事件我们的插件扫描帖子内容并将数据属性添加到链接,当再次刷新/重新打开帖子编辑页面时,控制台显示古腾堡验证错误。
<figure class="wp-block-image size-large">
<a href="http://affiliate.local/wp-admin/post.php?post=56662&action=edit" data-lasso-id="123">
<img src="http://affiliate.local/wp-content/uploads/2019/06/mint_2018_icon-toolbox-640x640.jpg" alt="" class="wp-image-51176"/>
</a>
</figure>
【问题讨论】:
标签:
wordpress
custom-data-attribute
wordpress-gutenberg
gutenberg-blocks
【解决方案1】:
经过多次尝试和错误,我得到了解决方案。
wp.hooks.addFilter(
"blocks.registerBlockType",
"sample-plugin/plugin/attribute/data",
(settings, name) => {
if (name == "core/image") {
settings.attributes = Object.assign( settings.attributes, {
'data-id': {
attribute: "data-id",
selector: "figure > a",
source: "attribute",
type: "string",
},
});
}
return settings;
}
);
function applyExtraClass( extraProps, blockType, attributes ) {
if(blockType.name != 'core/image') {
return extraProps;
}
try {
let figure_props = extraProps.children.props;
let first_child = figure_props.children[0];
if(figure_props.children && first_child && (first_child.type == 'a')) {
first_child.props['data-id'] = attributes["data-id"];
}
} catch (error) {
console.log(error);
}
return extraProps;
}
wp.hooks.addFilter(
'blocks.getSaveContent.extraProps',
'sample-plugin/plugin',
applyExtraClass
);