[英]Add user meta data as order meta on WooCommerce order status change
I am trying to add a custom user meta field to the order meta data.我正在尝试将自定义用户元字段添加到订单元数据。 And I want to add this when I am changing my order status to "wordt-verwerkt" which is a custom order status I added with the WooCommerce plugin for custom order statuses.
当我将订单状态更改为“wordt-verwerkt”时,我想添加它,这是我使用 WooCommerce 插件添加的自定义订单状态,用于自定义订单状态。 I tried to use the code from this post , but I am getting an error when I change my order status.
我尝试使用这篇文章中的代码,但是当我更改订单状态时出现错误。 (I also tried it with the status "processing", and didn't have any success neither)
(我也尝试过状态为“正在处理”,但也没有任何成功)
What I have now is the following code:我现在拥有的是以下代码:
add_action( 'woocommerce_order_status_wordt-verwerkt', 'add_order_meta_from_custom_user_meta', 10, 2 );
function add_order_meta_from_custom_user_meta( $order, $data ) {
$user_id = $order->get_user_id(); // Get the user id
if( $WefactEmail = get_user_meta( $user_id, 'KVK_nummer_2', true ) ) {
$order->update_meta_data( 'WeFact_email', $WefactEmail );
}
if( isset($WefactEmail) ) {
$order->save();
}
}
There are some mistakes in your code (the hooked function arguments are wrong).您的代码中有一些错误(挂钩的 function arguments 是错误的)。
See the related source code for this composite hook located in WC_Order
status_transition()
method (on line 363 ) :请参阅位于
WC_Order
status_transition()
方法中的此复合挂钩的相关源代码( 第 363 行) :
do_action( 'woocommerce_order_status_' . $status_transition['to'], $this->get_id(), $this );
where $this
is $order
(the WC_Order
Object) and $this->get_id()
is $order_id
(the order Id) .其中
$this
是$order
( WC_Order
对象) , $this->get_id()
是$order_id
(订单 ID) 。
Use instead the following:改用以下内容:
add_action( 'woocommerce_order_status_wordt-verwerkt', 'add_order_meta_from_custom_user_meta', 10, 2 );
function add_order_meta_from_custom_user_meta( $order_id, $order ) {
$user_id = $order->get_user_id(); // Get the user id
$wf_email = get_user_meta( $user_id, 'KVK_nummer_2', true );
if( ! empty($wf_email) ) {
$order->update_meta_data( 'WeFact_email', $wf_email );
$order->save();
}
}
or also this works too:或者这也有效:
add_action( 'woocommerce_order_status_wordt-verwerkt', 'add_order_meta_from_custom_user_meta', 10, 2 );
function add_order_meta_from_custom_user_meta( $order_id, $order ) {
$user_id = $order->get_user_id(); // Get the user id
$wf_email = get_user_meta( $user_id, 'KVK_nummer_2', true );
if( ! empty($wf_email) ) {
update_post_meta( $order_id, 'WeFact_email', $wf_email );
}
}
Code goes in functions.php file of the active child theme (or active theme).代码进入活动子主题(或活动主题)的functions.php文件。 both should work.
两者都应该工作。
For processing
status, replace:对于
processing
状态,替换:
add_action( 'woocommerce_order_status_wordt-verwerkt', 'add_order_meta_from_custom_user_meta', 10, 2 );
with:和:
add_action( 'woocommerce_order_status_processing', 'add_order_meta_from_custom_user_meta', 10, 2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.