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

自定义WordPress Gutenberg块重载编辑器时验证失败求助

Block验证失败问题修复方案

问题根源

  1. 属性定义未指定内容来源,Gutenberg无法正确识别保存的HTML结构,数据库读取时自动添加了<p>标签,导致与save函数生成内容不匹配。
  2. save函数未使用useBlockProps.save(),编辑态与保存态的根元素属性不一致。

1. 修改属性定义(package.json)

给quote和source添加source和selector,让Gutenberg明确从对应HTML标签读取内容:

"attributes": {
  "quote": {
    "type": "string",
    "source": "html",
    "selector": "blockquote"
  },
  "source": {
    "type": "string",
    "source": "html",
    "selector": "figcaption"
  }
}

2. 修复save.js的根元素属性

使用useBlockProps.save()保持与编辑态根元素结构一致:

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

export default function save(props) {
    return (
        <div { ...useBlockProps.save() } className="testimonial">
            <div className="testimonial__wrapper">
                <div className="testimonial__header">
                    <i className="testimonial__quote__left"></i>
                    <RichText.Content tagName="blockquote" value={ props.attributes.quote } />
                    <i className="testimonial__quote__right"></i>
                    <RichText.Content tagName="figcaption" value={ props.attributes.source } />
                </div>
            </div>
        </div>
    );
}

3. 可选:限制RichText格式(避免额外标签)

如果不需要富文本格式,可在edit的RichText中添加配置,防止自动生成<p>标签:

<RichText
    tagName="blockquote"
    value={props.attributes.quote}
    onChange={(content) => props.setAttributes({ quote: content })}
    placeholder='Enter Quote'
    keepPlaceholderOnFocus={true}
    multiline={false}
    formattingControls={[]}
/>

修改后,Gutenberg会通过指定的selector直接读取对应标签内容,不会自动添加<p>;同时编辑态与保存态的根元素属性一致,即可通过Block验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:32:36