如何使用 REST API Woocommerce 更新 acf 文件

问题描述 投票:0回答:1

我正在尝试通过 REST API 更新 Woocommerce 产品的自定义字段 (acf):

$acf_data = [
 "fields" => [
  'demo_url' => 'http://myurl'
  ]
];
$woocommerce_tn->put('/wp-json/acf/v3/product/'.$product_tn->id, $acf_data);

但这行不通。

wordpress woocommerce advanced-custom-fields wordpress-rest-api acfpro
1个回答
0
投票

Woocommerce API 内部使用

WC_REST_Products_Controller

产品创建的内部步骤之一调用

update_additional_fields_for_object()
方法,如果我们有办法在 WordPress 全局变量
$wp_rest_additional_fields
中注册我们的 ACF 字段,我们就可以利用它。

这是我创建的一个类来处理这个问题:

<?php

class Acf
{
    public const PRODUCT_FIELD_1 = 'field_650accdf92eaa';
    public const PRODUCT_FIELD_2 = 'field_650aaaaa761ed';

    public const PRODUCT_PROPERTIES = [
        self::PRODUCT_FIELD_1,
        self::PRODUCT_FIELD_2,
    ];

    public static function registerProductAcfFieldsForUpdate(): void
    {
        foreach (self::PRODUCT_PROPERTIES as $field) {
            self::registerProductRestForUpdate($field);
        }
    }

    protected static function registerProductRestForUpdate(string $attribute): void
    {
        register_rest_field(
            'product',
            $attribute,
            array(
                'update_callback' => 'Acf::updateAcfFieldsCallback',
            )
        );
    }

    /** @noinspection PhpUnused */
    public static function updateAcfFieldsCallback(
        $fieldValue,
        $product,
        $selector,
        $request,
        $objectType
    ): void {
        update_field($selector, $fieldValue, $product->get_id());
    }
}

只需从适当的挂钩调用

Acf::registerProductAcfFieldsForUpdate()
,如下所示:

add_action( 'rest_api_init', 'Acf::registerProductAcfFieldsForUpdate' ) );

它适用于我的项目

© www.soinside.com 2019 - 2024. All rights reserved.