Add order number as custom order item meta data in WooCommerce

I am trying to add the order number of a placed order to every single line item. We are using a order split plugin(https://woocommerce.com/products/split-orders/) and a order combination plugin.

So to be able to track where the product originally came from I would like to add the order number to the line item as meta data when an order is created.

I tried some things before, like the code below, but I am getting errors when trying to place an order:

function action_woocommerce_new_order( $order_get_id ) { 
    $items = $order_get_id->get_items();
    foreach ( $items as $item ) {
        $item->update_meta_data( 'order_nummer', $order_get_id );
        $item->save_meta_data();
    }
}

add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );

Can anyone help me in the right direction?

Best,

Answer

In the end I managed to make it work with the following code:

function print_order_line_item_meta( $items, $order ) {
   $order_number = $order->get_order_number();
   $items = $order->get_items();
   foreach ( $items as $item ) {
       $item->update_meta_data( '_org_ordernummer', $order_number );
       $item->save_meta_data();
   }
}
add_action( 'woocommerce_order_status_on-hold', 'print_order_line_item_meta', 10, 2 );

Because all my orders are starting with the status “on-hold”, I added the line item meta when the order has this status instead of adding it when the order is created. This is returning the order number instead of 0.

Leave a Reply

Your email address will not be published. Required fields are marked *