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

WP REST API PUT请求无法编辑property_meta字段问题咨询

根本原因

你没法通过REST API更新property_meta字段的原因非常明确:注册自定义REST字段时,你只定义了读取数据的get_callback,完全没有定义处理写入逻辑的update_callback。
WordPress的register_rest_field函数不会自动帮你处理自定义字段的写入,没有配置更新回调的字段,接口收到对应传参时会直接跳过不处理,这就是为什么请求返回200状态码,但字段值根本没有变化——核心根本没执行任何和这个字段更新相关的逻辑。

修复代码

把你现有的字段注册代码替换为以下版本,补充更新回调和必要的权限校验即可:

/*------------------------------------------------
 * Properties Meta Fields for rest API
 *----------------------------------------------- */
if( !function_exists('houzez_property_rest_api_field')) {
    add_action( 'rest_api_init', 'houzez_property_rest_api_field' );

    function houzez_property_rest_api_field() {
        register_rest_field( 'property', 'property_meta', array(
            'get_callback'    => 'houzez_get_rest_api_property_meta',
            'update_callback' => 'houzez_update_rest_api_property_meta',
        ) );
    }

    function houzez_get_rest_api_property_meta( $object ) {
        $post_id = $object['id'];
        $property_meta = get_post_meta( $post_id );
        $property_meta = apply_filters( 'houzez_property_rest_api_meta', $property_meta );
        return $property_meta;
    }

    /**
     * 处理property_meta字段的REST API写入逻辑
     */
    function houzez_update_rest_api_property_meta( $input_meta, $post_object, $field_name ) {
        $post_id = $post_object->ID;
        
        // 权限校验:仅拥有该文章编辑权限的用户可修改元数据
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return new WP_Error(
                'rest_forbidden',
                '无权限修改房产元数据',
                [ 'status' => 403 ]
            );
        }

        // 逐项更新传入的元数据
        if ( is_array( $input_meta ) ) {
            foreach ( $input_meta as $meta_key => $meta_value ) {
                // 建议在这里加元数据键名白名单,避免非法字段被修改,例如只允许更新fave开头的房产相关元数据
                if ( strpos( $meta_key, 'fave_' ) !== 0 ) {
                    continue;
                }
                update_post_meta( $post_id, $meta_key, $meta_value );
            }
        }
        return true;
    }
}
补充说明
  • 代码可以放到当前主题的functions.php文件或者自定义功能插件中,保存后重新发起之前的PUT请求即可正常更新价格字段
  • 代码里加了fave_前缀的白名单校验,如果你有其他非这个前缀的业务元数据需要修改,调整这个判断规则即可,加白名单是为了避免接口被滥用修改WordPress核心或其他插件的敏感元数据
  • 不需要修改你现有的curl请求格式,原有传参结构完全兼容

内容的提问来源于stack exchange,提问作者Juan mulero fuentes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 21:18:28