Question: Adding user custom field to the order meta-data automatically

Question

Adding user custom field to the order meta-data automatically

Answers 1
Added at 2016-12-30 01:12
Tags
Question

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.

Answers
nr: #1 dodano: 2016-12-30 01:12

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…

Source Show
◀ Wstecz