I've created two custom user profile fields which I also use as user meta data. When an order is created, I need this information to be saved as order metadata in Woocommerce.
I've created a function for each instance.
For the VAT Number:
add_action( 'woocommerce_checkout_create_order', 'wwp_customer_meta_data', 10, 2 );
function wwp_customer_meta_data( $order, $data ) {
$user_id = $order->get_user_id(); // Get the user id
$wwp_vat = get_user_meta( $user_id, 'wwp_wholesaler_tax_id', true );
$order->update_meta_data( 'VAT Number', $wwp_vat );
}
For the Company Number in my accounting software:
add_action( 'woocommerce_checkout_create_order', 'visma_customer_meta_data', 10, 2 );
function visma_customer_meta_data( $order, $data ) {
$user_id = $order->get_user_id(); // Get the user id
$billing_visma = get_user_meta( $user_id, 'billing_visma', true );
$order->update_meta_data( 'Billing Visma', $billing_visma );
}
How do I combine both functions into a single function?
I want to learn how to create code more efficiently.
You should do this:
add_action( 'woocommerce_checkout_create_order', 'add_customer_meta_data_to_order', 10, 2 );
function visma_customer_meta_data( $order, $data ) {
$user_id = $order->get_user_id(); // Get the user id
$billing_visma = get_user_meta( $user_id, 'billing_visma', true );
$order->update_meta_data( 'Billing Visma', $billing_visma );
$wwp_vat = get_user_meta( $user_id, 'wwp_wholesaler_tax_id', true );
$order->update_meta_data( 'VAT Number', $wwp_vat );
}