JonnyBravo
JonnyBravo

Reputation: 55

Passing Custom User Fields to WooCommerce Order Metadata

I'm working on setting up an Woo site that will be integrated with a Sage X3 ERP system. We will be pushing new orders through to Sage. Now I am looking to add a custom ID field for each customer and I was able to accomplish that with the ACF plugin. Now I just need to find a way to push that ID through to the order metadata so that Sage can correctly identify the customer.

enter image description here

What would be the best way to accomplish that? The name of the of the field is "Sage X3 Customer ID" with the key being "sagecustomerid". Any help would be appreciated.


Edit:

I feel like I'm getting close, as I see the 'sagecustomerid' in the order meta now based on this code:

add_action( 'woocommerce_checkout_create_order', 'before_checkout_create_order', 10, 2 ); 
function before_checkout_create_order( $order, $data ) { 
    $order->update_meta_data( 'sagecustomerid', '$value', $meta_id = 2746 ); 
} 

How can I get the value from db table posts ID 2746?

I can't seem to get it to work.

Upvotes: 1

Views: 1110

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254378

You don't need the meta ID in your function, so in your function code you will have:

$order->update_meta_data( 'sagecustomer', $some_value );  

But you need to get $some_value from somewhere…

This is about post meta data, but not post data, so the related database table is wp_postmeta for orders…

If the data you need come from user meta data, the code will be a bit different, like:

add_action( 'woocommerce_checkout_create_order', 'before_checkout_create_order', 10, 2 ); 
function before_checkout_create_order( $order, $data ) { 
    if ( $value = get_user_meta( $order->get_user_id(), 'sagecustomerid', true ) ) {
        $order->update_meta_data( 'sagecustomer', $value ); 
    } 
} 

Once done you will be able to get 'sagecustomer' meta value from:

  • The WC_Order Object using: $value = $order->get_meta('sagecustomer');
  • The order ID ($order_id) using: $value = get_post_meta($order_id, 'sagecustomer', true);

Upvotes: 1

Related Questions