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

在wp.blocks.registerBlockType的save函数中创建img块报错求解决

WordPress自定义图片块“Attempt Recovery”问题解决

问题根源

你的代码触发恢复提示主要有两个核心原因:

  1. 缺少alt属性:HTML规范强制要求img标签必须包含alt属性(即使是空值),WordPress块编辑器会严格校验可访问性规则,缺少该属性会被判定为无效内容。
  2. 块内容序列化不匹配:直接硬编码图片地址且未通过块的attributes管理数据,编辑器无法正确解析和序列化块内容,导致保存后校验失败。

修正后的完整代码

wp.blocks.registerBlockType('your-plugin/custom-image-block', {
    title: '自定义图片块',
    icon: 'format-image',
    category: 'common',
    // 定义块的属性,用于管理图片数据
    attributes: {
        imageSrc: {
            type: 'string',
            default: 'https://api.nasa.gov/assets/img/general/apod.jpg'
        },
        imageAlt: {
            type: 'string',
            default: 'NASA天文每日图'
        }
    },
    // 编辑模式渲染
    edit: (props) => {
        return wp.element.createElement('img', {
            src: props.attributes.imageSrc,
            alt: props.attributes.imageAlt,
            style: { maxWidth: '100%', height: 'auto' }
        });
    },
    // 保存模式渲染
    save: (props) => {
        return wp.element.createElement('img', {
            src: props.attributes.imageSrc,
            alt: props.attributes.imageAlt,
            className: props.className // 保留块默认类名,兼容WordPress样式
        });
    }
});

关键注意事项

  • 必须保留alt属性:即使不需要描述文本,也要设置alt: "",否则编辑器会持续触发校验错误。
  • 用attributes管理数据:不要硬编码内容,通过属性存储图片地址和描述,编辑器能正确序列化块数据,避免解析失败。
  • 保持edit与save输出一致:两个函数返回的元素结构、关键属性要匹配,编辑器会对比编辑态和保存态的内容,不一致就会触发恢复提示。
  • 添加className:使用props.className可以让块继承WordPress的默认块样式,也方便后续自定义样式控制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:26:22