3

woocommerce_new_order fires before order items are assigned to the order, thus making $order->get_items(); return an empty array.

Is there any way to get the items using that hook?

The order is created using wc_new_order so using woocommerce_checkout_order_processed won't work.

Is there another hook that could be used?

I'm using The Events Calendar and with it they have a functionality to move an event attendee from one event to another.

I use the hook tribe_tickets_ticket_moved (https://docs.theeventscalendar.com/reference/hooks/tribe_tickets_ticket_moved/) but for some reason(??) they do not pass the new order_id with the hook. So I resolved myself to check for new orders using woocommerce_new_order with a couple check to make sure the new order comes from the ticket moving and that its the right one.

They even set parent_id on the new order, but nothing on the old one to link them together.

I'm not sure how I could access the new order from the ticket_moved hook, or getting the items in the woocommerce_new_order hook.

Muhammad Zohaib
  • 307
  • 1
  • 5
  • 15
Antoine
  • 41
  • 1
  • You can get the order item from the order in the hook '`do_action( 'woocommerce_new_order', $order->get_id(), $order );` – mujuonly Jan 20 '23 at 15:06
  • 2
    @mujuonly $order->get_items() returns empty. the items have not yet been posted to the order – Antoine Jan 20 '23 at 16:48

1 Answers1

0

Since WooCommerce 4.3.0 the correct hook to be used to get $order->get_items(); is woocommerce_checkout_order_created.

function after_order_placed( $order ) {

    foreach ( $order->get_items() as $item_id => $item ) {

      $custom_meta = $item->get_meta('Custom Key');
  
    }

}
add_action( 'woocommerce_checkout_order_created', 'after_order_placed' );

This hook is located inside create_order() method for WC_Checkout Class.

Note: The code will not work for manual created orders via admin.

Muhammad Zohaib
  • 307
  • 1
  • 5
  • 15