【发布时间】:2021-03-04 11:41:04
【问题描述】:
我正在尝试通过运行Order action 将一些自定义元数据添加到 WooCommerce 订单。
这是我的代码:
function custom_add_order_actions( $actions ){
global $theorder;
$actions['my_custom_action'] = 'My custom action';
return $actions;
}
add_action( 'woocommerce_order_actions', 'custom_add_order_actions' );
function custom_add_single_action( $order ){
// Non of these change anything on the order
$order->set_billing_first_name( 'A new test name' );
$order->update_post_meta( 'a_test_field', 'Test field value' );
update_post_meta( $order->get_id(), 'a_test_field', 'Some other value' );
// $order->save(); // I even tried adding this as well, but it doesn't change anything.
}
add_action( 'woocommerce_order_action_my_custom_action', 'custom_add_single_action' );
如何从操作中更改订单(或具体来说,订单的 post_meta 字段)?
一个例子
假设我添加了一个 post_meta 字段,其字段名称(键):a_test_field。
它目前是一个 ACF 字段,但对于常规的 WordPress 自定义字段来说是一样的。
如果我更改字段的值并按“更新”,则值会更改:
到目前为止一切顺利。现在该字段的值为 'Foobar'。
奇怪的是,即使我这样做:
add_action( 'woocommerce_order_action_my_custom_action', 'custom_add_single_action' );
function custom_add_single_action( $order ){
update_post_meta( $order->get_id(), 'a_test_field', 'A new value' );
die(); // This die is vital, to make the change in the database.
}
然后我可以看到数据库中的值更改为“新值”。
但如果我这样做:
add_action( 'woocommerce_order_action_my_custom_action', 'custom_add_single_action' );
function custom_add_single_action( $order ){
$order->update_post_meta( 'a_test_field', 'A new value' );
// No die(); here...
}
那么数据库中的值仍然是“Foobar”。
【问题讨论】:
标签: woocommerce