I need to change the normal behavior of the place_order
button at checkout: if there’s already an order which is not completed (status = processing), WooCommerce should add items to that order instead of creating a new one. Otherwise, it should create a new order in the default way.
function custom_order() {
$user_role = wp_get_current_user()->roles[0];
$customer = new WC_Customer($user_id);
$last_order = $customer->get_last_order();
$last_order_id = $last_order->get_id();
$last_order_data = $last_order->get_data();
$last_order_status = $last_order->get_status();
if ( $user_role === "administrator" ) {
if ($last_order_status === "processing") {
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
$product_id = $product->get_id();
$quantity = $product->get_quantity();
$last_order->add_product($product, $quantity);
}
}
else {
// do the normal thing
}
}
}
I’ve tried the following hooks:
add_action('woocommerce_new_order', 'custom_order', 10, 3);
add_filter('woocommerce_create_order', 'custom_order', 10, 2);
Which is the right one and how to add this new condition to the default order function?
2
Answers
Inside the class
class-wc-checkout.php
, the create_order function provides a hook just before creating the order. It will not create another order if the order ID already exist. We will return the order ID if the conditions met.The
woocommerce_create_order
filter hook is indeed the right hook to use for your question.However, when just using
$last_order->add_product( $product, $quantity );
you will notice 2 issuesSo what you need to do is, in addition to loop through the cart items, also loop through the existing order items and compare them.
If the item already exist, update the item, if not, add the item to the order
The second param
$checkout
enable you to compare and adjust billing information and such if desiredSo you get:
Related: Split a WooCommerce order and create a new order if the original order has products in backorder