自定义WordPress Gutenberg块重载编辑器时验证失败求助
Block验证失败问题修复方案
问题根源
- 属性定义未指定内容来源,Gutenberg无法正确识别保存的HTML结构,数据库读取时自动添加了
<p>标签,导致与save函数生成内容不匹配。 - 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
相关产品推荐
相关产品推荐

