I've been trying to implement a custom discount on my WooCommerce store for some time now, either through looping all products and setting a new price with set_price()
or through adding a negative fee with add_fee()
. Both approaches work on the cart page but when going to the checkout I can see the discounted price for a few seconds, but when the spinning wheel is finalized the old regular price it replaces the discounts (the fee completely disappears).
An example of the many codes I have tried in my childs functions.php:
add_action('woocommerce_before_calculate_totals', 'cart_item_discount', 10, 1 );
function cart_item_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetition (when using price calculations for example)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop Through cart items
foreach ( $cart->get_cart() as $cart_item ) {
$original_price = $cart_item['data']->get_price(); // Get original product price
$discounted_price = $original_price / 2; // 50 % of discount
$cart_item['data']->set_price( $discounted_price );
}
}
I have been troubleshooting and from what I can tell, an AJAX call through ?wc-ajax=update_order_review
is done 1-2 seconds after entering the checkout, which is what causes the overwriting. The call returns a status 200 with fragments, and those fragments include the old regular price instead of the new ones.
How can I disable this AJAX call on the checkout page so the discount code works properly?
I have tried both on local and production server. I have tried installing a new fresh WordPress/WooCommerce install with a new database, removed all other plugins. Using WordPress 5.0.3, WooCommerce 3.5.4, Child theme of Storefront 2.4.2.