简体   繁体   中英

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. 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).

See the related source code for this composite hook located in WC_Order status_transition() method (on line 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) .

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). both should work.

For processing status, replace:

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM