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?
add_filter('woocommerce_create_order', 'create_or_update_order', 10, 2);
function create_or_update_order() {
$user_obj = wp_get_current_user();
$user_role = $user_obj->roles[0];
$user_id = $user_obj->ID;
$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 ('administrator' === $user_role) {
if ('processing' === $last_order_status) {
foreach (WC()->cart->get_cart() as $cart_item) {
$product = $cart_item['data'];
$product_id = $product->get_id();
$quantity = $cart_item['quantity'];
$last_order->add_product($product, $quantity);
}
return $last_order_id;
} else {
return null;
}
}
return null;
}
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.
public function create_order( $data ) {
// Give plugins the opportunity to create an order themselves.
$order_id = apply_filters( 'woocommerce_create_order', null, $this );
if ( $order_id ) {
return $order_id;
}......