I am using WooCommerce subscriptions plugin in WooCommerce. I am trying to write a function to perform a 10% discount on normal products when one of the following conditions are met:
- The User Has an Active Subscription
- The User has a Subscription Product in his cart
function vip_discount() {
$woocommerce = WC();
$items = $woocommerce->cart->get_cart();
$vip_product_id = get_subscription_product_id();
$is_vip_in_cart = is_in_cart($vip_product_id);
$vip_product_price = 0;
foreach ($items as $item) {
if( $item['variation_id'] === get_subscription_variation_id('monthly') || $item['variation_id'] === get_subscription_variation_id('quarterly') || $item['variation_id'] === get_subscription_variation_id('annually') ) {
$vip_product_price = $item['line_total'];
}
}
if ( wcs_user_has_subscription( '', '', 'active' ) || $is_vip_in_cart ) {
// Make sure that the calculation is a negative number at the end ALWAYS!
$discount = -( 10 / 100 ) * ( $woocommerce->cart->get_displayed_subtotal() - $vip_product_price);
print_r($discount);
$woocommerce->cart->add_fee( 'VIP Discount', $discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'vip_discount' );
The problem is that this hook is for some reason run twice. Also it's not applying the correct fee. It's supposed to subtract the recurring items total from the negatively applied fee, instead the fee is ending up as the subscription (recurring) product price itself.
Any supplementary information or help is appreciated.