Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a discount programmatically to an Order in Woocommerce 3.2+

In woocommerce, we can add a discount to any order using Coupons feature (fixed amount, percent amount…).

Is it possible to add discount amount to any order programmatically where the discount amount can be any amount?

Any help will be appreciated.

like image 798
Pankaj Verma Avatar asked Oct 04 '18 12:10

Pankaj Verma


People also ask

How do I add a percentage discount in WooCommerce?

The first way is to add a percentage off coupon. To do this, go to WooCommerce > Coupons and click on Add Coupon. Then, enter a coupon code and enter the amount you want to take off in the Discount Amount field. In the Discount Type dropdown, select Percent Off.


1 Answers

Actually you can just make hook before calculate tax etc, get subtotal, apply discount, done :) It automatically apply for Order message etc, it is visible also in backend in proper way. Even after remove hook, info about discount stay in order information.

// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_user_discounts');
/**
 * Add custom fee if more than three article
 * @param WC_Cart $cart
 */
function add_user_discounts( WC_Cart $cart ){
    //any of your rules
    // Calculate the amount to reduce
    $discount = $cart->get_subtotal() * 0.5;

    $cart->add_fee( 'Test discount 50%', -$discount);
}
like image 79
Isu Avatar answered Oct 12 '22 15:10

Isu