通过 REST API v3 更新 ACF

问题描述

我已经向我的 WooCommerce 网站添加了一堆自定义字段 - 它们在产品页面显示良好,现在我已经添加了下面的代码,我可以通过 API 返回它们 - 但我无法更新他们通过 API - 希望我错过了一些非常明显的东西:)

我的代码(使用 PHP Inster 添加):-

function create_ACF_Meta_in_REST() {
    $postypes_to_exclude = ['acf-field-group','acf-field'];
    $extra_postypes_to_include = ["post"];
    $post_types = array_diff(get_post_types(["_builtin" => false],'names'),$postypes_to_exclude);

    array_push($post_types,$extra_postypes_to_include);

    foreach ($post_types as $post_type) {
        register_rest_field( $post_type,'ACF',[
            'get_callback'    => 'expose_ACF_fields','update_callback' => 'update_ACF_fields','schema'          => null,]
     );
    }
}

function update_ACF_fields( $data,$object ) {
    $ID = $object['id'];
    return  update_post_Meta(  $ID,$data );
}

function expose_ACF_fields( $object ) {
    $ID = $object['id'];
    return get_fields( $ID );
}

add_action( 'rest_api_init','create_ACF_Meta_in_REST' );

任何指针将不胜感激

解决方法

修复它 - 最后很容易,只是一个未记录的功能!

对于“标准”WooCommerce 字段,您可以像这样发送 JSON:-

{
"regular_price": "1.25"
}

这工作正常,并将更新您在端点中提供的 ID 的字段

但是

对于自定义字段,您必须发送以下内容:-

{
"key": "your field name"
"value": "your new value"
}

在没有我在问题中展示的任何额外代码的情况下,这样做可以正常工作

最后一切都好:)