skip to Main Content

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,

2

Answers


  1. Chosen as 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.


  2. You are not using the right hook… Try the following instead:

    add_action('woocommerce_checkout_create_order_line_item', 'action_checkout_create_order_line_item', 10, 4 );
    function action_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
        $item->update_meta_data( 'order_number', $order->get_order_number() );
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should better work.

    Note: If you want this custom order item meta data to be only visible in admin orders, use the meta key _order_number instead of order_number.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search