将WooCommerce订单项目自定义字段总和保存为新的元数据
在此WooCommerce商店中订购特定产品时,两个元值将添加到该订单中.
When a particular product is ordered in this WooCommerce store, two meta values are added to the order.
存储元值的两个字段位于wp_woocommerce_order_itemmeta
The two fields that store the meta values are located in wp_woocommerce_order_itemmeta
元键是:
quantity
assemblycost
我想在下达新订单时以编程方式创建一个新的自定义字段,并且如果已订购的产品存在元密钥assemblycost,则将该新字段的值设置为等于quanity * assemblycost
.
I want to create a new custom field programmatically when a new order is placed and set the value of this new field equal to quanity * assemblycost
if the meta key assemblycost exists for the product that has been ordered.
经过一些研究,我发现woocommerce_checkout_update_order_meta
是一个将订单保存到数据库并且元数据已更新后执行的钩子.因此,这似乎是我应该使用的钩子.
After some research I discovered that woocommerce_checkout_update_order_meta
is a hook that is executed after an order is saved to the database and the meta data has been updated. So this appears to be the hook I should use.
function add_item_meta( $order_id ) {
//global $woocommerce;
update_post_meta( $order_id, '_has_event', 'yes' );
}
我尝试在functions.php中添加以下代码:
I tried adding the following code, in functions.php:
add_action('woocommerce_checkout_update_order_meta',function( $order_id, $posted ) {
$assemblycost = wc_get_order_item_meta($order_id, 'assemblycost');
$quantity = wc_get_order_item_meta($order_id, 'quantity');
$calculatedValue = $quantity * $assemblycost;
wc_update_order_item_meta( $order_id, 'calculated_field', $calculatedValue );
} , 10, 2);
这确实创建了新的meta字段,但是将其值设置为0.
This does create the new meta field, however it sets the value to 0.
如何更改上面的代码,以使calculated_field的值等于quantity * assemblycost
的乘积?
How can I change the code above so that the value of calculated_field is the multiplication of quantity * assemblycost
?
这与订单商品有关,应保存为订单商品元数据,而不要保存为订单元数据.
This is related to order items and should be saved as order item meta data but not as order meta data.
现在应与两个自定义字段quantity
和assemblycost
一起保存.因此,您应该在问题中提供将quantity
和assemblycost
保存为订单项元数据的相关代码.
Now this should be saved at the same time than your 2 custom fields quantity
and assemblycost
. So you should provide in your question the related code that save quantity
and assemblycost
as order item meta data.
您可以尝试以下操作(但是我不确定我是否可以工作):
You can try the following (but I am not sure that I will work):
add_action( 'woocommerce_checkout_create_order_line_item', 'action_checkout_create_order_line_item_callback', 1000, 4 );
function action_checkout_create_order_line_item_callback( $item, $cart_item_key, $cart_item, $order ) {
$quantity = $item->get_meta('quantity');
$assemblycost = $item->get_meta('assemblycost');
if( isset($quantity) && isset($assemblycost) ) {
$item->update_meta_data( 'calculated_field', $quantity * $assemblycost );
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中.
Code goes in function.php file of your active child theme (or active theme).