I am currently importing orders from a marketplace to WooCommerce using the WooCommerce Rest API v3. The Marketplace Order ID is added in the Customer Note Field in the WooCommerce order upon import. The WooCommerce Order number is auto assigned from WooCommerce. I would like to use a Code Snippet to change the WooCommerce order number to the marketplace order ID stored in the WooCommerce Order's customer Note field when the order is imported to WooCommerce.
After reviewing the WooCommerce Rest API (Orders) Docs, I am still not sure if I need to update the number or order_key to achieve this.
Highlighted in yellow is the number I am looking to replace:
This is the Code Snippet I have, but that is not working:
function update_woocommerce_order_key( $order_id ) {
// Get the order object
$order = wc_get_order( $order_id );
if ( ! $order ) {
return;
}
// Get the customer note
$customer_note = $order->get_customer_note();
// Check if the customer note is not empty
if ( ! empty( $customer_note ) ) {
// Update the order key meta field
update_post_meta( $order_id, '_order_key', $customer_note );
// Update the order key in the order object
$order->set_order_key( $customer_note );
$order->save();
}
}
add_action( 'woocommerce_api_create_order', 'update_woocommerce_order_key', 10, 1 );
Any suggestions how to solve this?
I have tried the order_id, number, order_key upon import but nothing takes effect.
I would expect the WooCommerce Order Number to be updated with the order number from the Custom Note.
Instead of importing the original marketplace order number as an order note, you should directly import it as "_order_number" custom order metadata, inserting in your request something like:
"meta_data": [
{
"key": "_order_number",
"value": $marketplace_order_number,
}
]
Then, once done, you can use the following filter hook to alter the displayed order number:
// Displayed order number from custom metadata
add_filter( 'woocommerce_order_number', 'displayed_custom_order_number', 10, 2 );
function displayed_custom_order_number( $order_id, $order ) {
if ( $order_number = $order->get_meta('_order_number') ) {
return $order_number;
}
return $order_id;
}
Code goes in functions.php file of your child theme (or in a plugin). It should work.