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

WordPress自定义块中useEntityProp生产环境返回undefined问题

自定义块useEntityProp生产环境返回undefined问题

我通过Blocks API创建了自定义块,使用useEntityProp获取/设置文章元数据(post meta),该功能在开发服务器正常运行,但生产服务器中useEntityProp返回undefined。

上下文已返回正确的文章类型(postType)和文章ID(postId),且已注册文章元数据并启用show_in_rest选项。

编辑组件代码(console.log(meta)返回undefined)

import { __ } from "@wordpress/i18n";
import { MediaUpload, useBlockProps } from "@wordpress/block-editor";
import { useEntityProp } from "@wordpress/core-data";
import { Button } from "@wordpress/components";

const Edit = (props) => {
  let {
    attributes: { foundFeatures, features, gallery, itinerary, duration },
    setAttributes,
    context: { postType, postId },
  } = props;

  let [meta, updateMeta] = useEntityProp("postType", postType, "meta", postId);
};

注册文章元数据的PHP代码

register_post_meta(
    'tour-collection',
    'locations',
    array(
        'show_in_rest'       => true,
        'single'             => true,
        'type'               => 'string',
    )
);

可能的原因及解决办法

  • REST API权限与字段暴露
    注册元数据时添加auth_callback验证权限,生产环境权限检查更严格:

    register_post_meta(
        'tour-collection',
        'locations',
        array(
            'show_in_rest'       => true,
            'single'             => true,
            'type'               => 'string',
            'auth_callback'      => function() {
                return current_user_can('edit_posts');
            }
        )
    );
    

    清除WordPress缓存及服务器缓存,避免show_in_rest设置因缓存未生效。

  • 异步加载处理
    useEntityProp为异步获取数据,生产环境初始渲染时meta可能为undefined,添加加载状态判断:

    const Edit = (props) => {
      let {
        attributes: { foundFeatures, features, gallery, itinerary, duration },
        setAttributes,
        context: { postType, postId },
      } = props;
    
      let [meta, updateMeta] = useEntityProp("postType", postType, "meta", postId);
    
      if (!meta) {
          return <div>加载中...</div>;
      }
    
      // 后续业务逻辑
    };
    
  • 生产构建问题
    重新构建并部署代码,确保@wordpress/core-data模块未被错误压缩或树摇。

  • 自定义文章类型REST支持
    确认自定义文章类型tour-collection已启用REST API支持,注册时需设置:

    register_post_type( 'tour-collection', array(
        // 其他配置项
        'show_in_rest' => true,
        'rest_base' => 'tour-collections',
    ) );
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 12:45:18