В настоящее время я код следующий:
Код: Выделить всё
/* Dividing orders with multiple products and delivery destinations into different orders */
add_action( 'woocommerce_checkout_order_processed', 'split_order_by_destination', 10, 1 );
function split_order_by_destination( $order_id ) {
$main_order = wc_get_order( $order_id );
if ( ! $main_order ) {
write_to_wc_log( 'Main order not found for order ID: ' . $order_id );
return;
}
$destination_groups = [];
// Group order items by `Destination` meta
foreach ( $main_order->get_items() as $item_id => $item ) {
$destination = $item->get_meta( 'Destination', true );
write_to_wc_log( 'Order Item ID: ' . $item_id . ', Destination: ' . $destination );
if ( ! $destination ) {
$destination = 'default'; // Handle items without a destination
}
write_to_wc_log( 'Processing Item ID: ' . $item_id . ', Destination: ' . $destination );
if ( ! isset( $destination_groups[ $destination ] ) ) {
$destination_groups[ $destination ] = [];
}
$destination_groups[ $destination ][] = $item;
}
write_to_wc_log( 'Destination Groups: ' . print_r( $destination_groups, true ) );
if ( empty( $destination_groups ) ) {
write_to_wc_log( 'No destination groups found. Exiting splitting process.' );
return;
}
// Process each destination group
foreach ( $destination_groups as $destination => $items ) {
$new_order = wc_create_order();
if ( ! $new_order ) {
write_to_wc_log( 'Failed to create new order for destination: ' . $destination );
continue;
}
// Copy customer details from the main order
$new_order->set_address( $main_order->get_address( 'billing' ), 'billing' );
$new_order->set_address( $main_order->get_address( 'shipping' ), 'shipping' );
foreach ( $items as $item ) {
$product = wc_get_product( $item->get_product_id() );
if ( $product ) {
$new_order->add_product(
$product,
$item->get_quantity(),
[
'subtotal' => $item->get_subtotal(),
'total' => $item->get_total(),
'tax' => $item->get_subtotal_tax(),
]
);
write_to_wc_log( 'Added Product ID: ' . $product->get_id() . ' to order for Destination: ' . $destination );
}
}
$new_order->calculate_totals();
$new_order->save();
write_to_wc_log( 'Created New Order ID: ' . $new_order->get_id() . ' for Destination: ' . $destination );
$new_order->add_order_note( 'Order created for destination: ' . $destination );
}
// Optionally cancel the main order
$main_order->update_status( 'cancelled', 'Order split into multiple orders by destination.' );
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... estination
Мобильная версия