我已经向我的 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"
}
这样做可以很好地工作,无需我在问题中显示的任何附加代码
最后一切都好:)