Add this to your theme’s functions.php file
- Keep only 1 product in the original order, delete other products from this order.
- Place the removed products (each separately) in a new order.
function lpj_woocommerce_checkout_order_processed( $order_id, $posted_data, $order ) {
// Get order currency
$order_currency = $order->get_currency();
// Get order payment method
$order_payment_gateway = $order->get_payment_method();
// Address
$order_address = array(
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone(),
'address_1' => $order->get_billing_address_1(),
'address_2' => $order->get_billing_address_2(),
'city' => $order->get_billing_city(),
'state' => $order->get_billing_state(),
'postcode' => $order->get_billing_postcode(),
'country' => $order->get_billing_country()
);
// Shipping
$order_shipping = array(
'first_name' => $order->get_shipping_first_name(),
'last_name' => $order->get_shipping_last_name(),
'address_1' => $order->get_shipping_address_1(),
'address_2' => $order->get_shipping_address_2(),
'city' => $order->get_shipping_city(),
'state' => $order->get_shipping_state(),
'postcode' => $order->get_shipping_postcode(),
'country' => $order->get_shipping_country()
);
// Counter
$counter = 1;
// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
// From the 2nd product
if ( $counter >= 2 ) {
// Get the WC_Product Object
$product = $item->get_product();
// Get product quantity
$product_quantity = $item->get_quantity();
// Create new order
$new_order = wc_create_order();
// Add product to new order
$new_order->add_product( $product, $product_quantity );
// Set addresses
$new_order->set_address( $order_address, 'billing' );
$new_order->set_address( $order_shipping, 'shipping' );
// Set the correct currency and payment gateway
$new_order->set_currency( $order_currency );
$new_order->set_payment_method( $order_payment_gateway );
// Calculate totals
$new_order->calculate_totals();
// Set order note with original ID
$new_order->add_order_note( 'Automated order. Created from the original order ID: ' . $order_id );
// Set correct status
$new_order->update_status( 'processing' );
// Delete product from original order
$order->remove_item( $item_id );
}
// Counter = counter + 1
$counter++;
}
// Re-calculate & save
$order->calculate_totals();
$order->save();
}
add_action( 'woocommerce_checkout_order_processed', 'lpj_woocommerce_checkout_order_processed', 10, 3 );