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

使用JavaScript向WordPress Gutenberg编辑器添加内容后报错求助

问题原因

你传入core/paragraph块的content是HTML实体转义后的字符串(如<h1>),但该块的content字段要求接收原始HTML内容。保存后Gutenberg重新解析时,会将这些转义实体识别为普通文本而非HTML标签,导致块的实际结构与预期不符,触发内容校验错误。

解决方案

1. 解码HTML实体为原始HTML

先把转义后的字符串解码成可直接使用的HTML,再传入块的content属性。

2. 简化块操作流程

你代码里的serialize、parse、replaceBlock都是多余操作,直接创建并插入块即可。

修正后的代码:

// 转义的原始内容
let escapedContent = `<h1>What is Lorem Ipsum?</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>`;

// 解码HTML实体
const parser = new DOMParser();
const decodedContent = parser.parseFromString(escapedContent, 'text/html').body.textContent;

// 创建并插入段落块
const newBlock = wp.blocks.createBlock('core/paragraph', { content: decodedContent });
wp.data.dispatch('core/block-editor').insertBlock(newBlock, wp.data.select('core/block-editor').getBlockCount());

// 保存文章
wp.data.dispatch('core/editor').savePost();

额外注意事项

  • 如果你的API返回的就是转义后的HTML,直接在前端解码再传入块即可;如果API能返回原始HTML,可省去解码步骤。
  • core/paragraph块支持在content中包含嵌套HTML标签,但如果要单独的标题块,建议直接创建core/heading块,而非在段落块里嵌套<h1>,这样更符合Gutenberg的块结构规范,也能避免潜在的校验问题。

内容的提问来源于stack exchange,提问作者Syed Ali Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:57:27