Reputation: 121
I have a shipping discount in my woocommerce site, I would like to show it on cart page and checkout page, for that I used add_fee()
method.
WC()->cart->add_fee( 'Shipping Discount', -20, false );
It subtract 20 from total amount, but when I go to check order in orders inside admin it gives discount on tax too according to tax rate I configured. Is there any alternative to add discount
How can I do this in woocommerce?
Upvotes: 1
Views: 3413
Reputation: 101
You can use woocommerce_cart_totals_get_fees_from_cart_taxes
filter in WooCommerce for disable tax in fee:
add_filter('woocommerce_cart_totals_get_fees_from_cart_taxes', 'my_filter', 20, 3);
function my_filter($array_taxes, $fee, $object)
{
if (isset($fee->object->name) and $fee->object->name == 'YOUR_FEE_NAME_WITH_NEGATIVE_PRICE') {
return [];
}
return $array_taxes;
}
Related:
https://wp-kama.com/plugin/woocommerce/function/WC_Cart_Totals::get_fees_from_cart#L322
Upvotes: 0
Reputation: 254483
For negative cart fee there is a bug related to taxes as they are applied on all tax classes even if the it's not taxable.
Now you can make a custom global cart discount This way where you will be able to define the type of discount you want, the discount amount and the source price to be discounted.
This code will display the he correct cart discounted gran total
Once submitted this discounted gran total will be passed to the order.
The code:
// Apply a discount globally on cart
add_filter( 'woocommerce_calculated_total', 'discounted_calculated_total', 10, 2 );
function discounted_calculated_total( $total, $cart ){
$amount_to_discount = $cart->cart_contents_total;
$percentage = 10; // 10% of discount
$discounted_amount = $amount_to_discount * $discount / 100;
$new_total = $total - $discounted_amount;
return round( $new_total, $cart->dp );
}
Code goes in function.php file of the active child theme (or active theme).
Tested and works.
You should need to make some additional code to display the discount amount (in cart and checkout pages and order-view) and to pass it in the order as meta data and so on…
Upvotes: 1