I am creating my order like so:
$order = wc_create_order();
$product = wc_get_product( $_POST["product"] );
$order->add_product( $product, 1 );
$kupon = new WC_Coupon( $_POST["coupon"] );
$amount = $kupon->get_discount_amount( $product->price );
$order->add_coupon( $_POST["coupon"], $amount, $amount );
$order->calculate_shipping();
$order->calculate_totals();
If you take a closer look, I am adding a coupon code dynamicaly with add_coupon function from WC_Order class. Everythings works perfectly, the order is added to database with correct product, quantites, and ALSO the coupon is added – but the problem is that coupon is not “applied” to the total. It is not deducting the totals price. Here is the image:
While adding a product to an Order, we should pass an argument containing subtotal and total like this:
Where
$product
is Woocommerce product. Hope this helps somebody.Here is the solution that worked in my case for modifying order line items then applying a discount afterward – $order is a WC_Order object:
Here is the method to retrieve the coupon code for a WC_Order object. In my case I know there will never be more then 1 coupon per order so you may want to adjust it to accommodate more: