我正在尝试通过 REST API 更新 Woocommerce 产品的自定义字段 (acf):
$acf_data = [
"fields" => [
'demo_url' => 'http://myurl'
]
];
$woocommerce_tn->put('/wp-json/acf/v3/product/'.$product_tn->id, $acf_data);
但这行不通。
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' ) );
它适用于我的项目