Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access order items in the hook woocommerce_new_order?

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.

like image 558
Antoine Avatar asked Oct 18 '25 15:10

Antoine


1 Answers

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.

like image 71
Muhammad Zohaib Avatar answered Oct 20 '25 16:10

Muhammad Zohaib