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

WordPress Gutenberg自定义块保存后编辑出现HTML验证错误

Gutenberg自定义块验证错误排查与解决

问题场景

使用@wordpress/create-block开发自定义Gutenberg块,通过RichText组件实现quote(引用)和author(作者)输入功能,保存块后重新编辑页面时触发块验证错误,提示save函数返回的HTML与数据库存储内容不一致,quote和author属性值出现拼接情况。

问题原因

  1. 属性选择器不精准:在block.js的属性配置中,quote和author的selector都设置为div,Gutenberg解析数据库中的HTML时,会将所有div标签的文本内容拼接后同时赋值给这两个属性,导致属性值与预期不符,进而让save函数生成的HTML和数据库存储内容不匹配,触发验证错误。
  2. RichText内容渲染方式错误:save函数中直接输出属性字符串,没有使用RichText.Content组件处理RichText内容,可能导致内容解析或格式还原出现偏差。

解决方案

1. 修正属性选择器配置

修改block.js中的attributes配置,为每个属性指定精准的selector,确保Gutenberg能正确提取对应元素的文本:

"attributes": {
    "quote": {
        "type": "string",
        "source": "text",
        "selector": "div.quote"
    },
    "author": {
        "type": "string",
        "source": "text",
        "selector": "div.author"
    }
}

2. 修正save函数的内容渲染方式

在save.js中使用RichText.Content组件渲染RichText内容,确保内容的格式和解析逻辑与编辑时一致:

import { RichText, useBlockProps } from '@wordpress/block-editor';

export default function save({ attributes }) {
    const blockProps = useBlockProps.save()
    const { quote, author } = attributes

    return (
        <div { ...blockProps }>
            <RichText.Content
                tagName="div"
                className="quote"
                value={ quote }
            />
            <RichText.Content
                tagName="div"
                className="author"
                value={ author }
            />
        </div>
    );
}

3. 处理旧内容

如果数据库中已有保存的旧块内容,需要重新编辑并保存这些块,让新的属性解析规则生效,确保后续编辑不会再出现验证错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:32:32