For some custom functionality in Woocommerce, I need to copy order items with all metadata from one order to another order programatically. The source order is of type WC_Order
while destination order type is WC_Subscription
which extends WC_Order
and is a custom order type.
I have tried with a following function but it doesn't work. Although the order total is updated which matches to source order but the items in order are not added.
function wc_copy_order_items( &$from_order, &$to_order ) {
if ( ! is_a( $from_order, 'WC_Abstract_Order' ) || ! is_a( $to_order, 'WC_Abstract_Order' ) ) {
throw new InvalidArgumentException( _x( 'Invalid data. Orders expected aren\'t orders.', 'In wc_copy_order_items error message. Refers to origin and target order objects.', 'woocommerce-subscriptions' ) );
}
$from_order_all_items = $from_order->get_items( array( 'line_item', 'fee', 'shipping' ) );
foreach( $from_order_all_items as $item ) {
$to_order->add_item( $item );
}
$to_order->save();
}
I have also tried with woocommerce admin function wc_save_order_items
by hooking into woocommerce_process_shop_order_meta
while saving source order from admin but that also results in only update in totals of destination order and do not add items.
wc_save_order_items( $source_order_id, $_POST );
Basically, I want to copy all the data including all meta data and custom fields from source order to destination order. I've managed to copy other metadata by somehow but I can't get it right for copying order items with item metadata.
Please help me to find why above function doesn't work and guide me for a solution to copy order items between two orders.