2
votes

Is it possible to automatically copy the value of a Customer's custom field to an Order's custom field when this customer places the order?

Should it be done using any plugin/extension or thru customized coding behind the scenes?

This custom field does not need to be displayed on customer order view. We just need it to distinguish whether the order was placed by Consumer or Wholesale when we get it thru API.

I'm totally new in this system, i did a lot of research but couldn't find any direction for this.

Any advice/suggestion would be very appreciated.

1
thank you for your quick response, @LoicTheAztec! I just edited the question, hopefully it makes sense to you.Zark
thanks a lot, @LoicTheAztec it's a very nice piece of code. I had marked it as answer. I will try it out and let you know if i get stuck somewhere :)Zark
Is there any way to get this to work when you create an order manually from the back-end?Wanderlust Consulting
@LoicTheAztec, can you confirm if my solution achieves the same objective? You can see it here: stackoverflow.com/questions/68793013/…Wanderlust Consulting

1 Answers

3
votes

You can use woocommerce_thankyou hook to add this user data to the order meta data:

add_action( 'woocommerce_thankyou', 'orders_from_processing_to_pending', 10, 1 );
function orders_from_processing_to_pending( $order_id ) {

    if ( ! $order_id )
        return;

    $order = wc_get_order( $order_id );
    $user_id = get_current_user_id();

    //Set HERE the meta key of your custom user field
    $user_meta_key = 'some_meta_key';

    // Get here the user custom field (meta data) value
    $user_meta_value = get_user_meta($user_id, $user_meta_key, true);


    if ( ! empty($user_meta_value) )
        update_post_meta($order_id, $user_meta_key, $user_meta_value);
    else
        return;

}

Code goes in function.php file of your active child theme (active theme or in any plugin file).

This code is tested and works.

After, if you want to display that value on admin edit order backend or in frontend customer view order and emails notifications, you will have to use some more code and some other hooks…