Add product to cart with hook, discount applies after refresh of page


I have this simple setup where I add a product to the cart as a gift if conditions are met like so:

add_action( 'woocommerce_before_cart', 'apply_membership_benefits' );
function apply_membership_benefits() {
  global $woocommerce;  
  // Get the cart subtotal in non-decimal number format
  $cart_subtotal = WC()->cart->subtotal;
  $product_id1 = 9617; // membership product    
  $product_id2 = 9616; //  custom bottle product    
  // If cart subtotal is less than 800 remove benefits
  if ($cart_subtotal < 800) {
      WC()->cart->remove_cart_item( WC()->cart->generate_cart_id( $product_id1 ) );
      WC()->cart->remove_cart_item( WC()->cart->generate_cart_id( $product_id2 ) );
  // If cart above 800 add membership benefits
  if ($cart_subtotal > 799 ) {
    $item_key_inc_cart = WC()->cart->add_to_cart( $product_id1 );
    WC()->cart->set_quantity( $item_key_inc_cart,1 );
    $item_key_inc_cart = WC()->cart->add_to_cart( $product_id2 );
    WC()->cart->set_quantity( $item_key_inc_cart,1 );

The cart will work correctly only I also have a discount plugin that also applies a discount to this cart of 20%. The problem is the discount is applied if the user is refreshing the page so the cart content seems to be read before the woocommerce_before_cart hook.

Consequently if I remove one product from the cart adn the subtotal will be below 800 as shown in the example the gifts will be removed but the discount is still applied and needs a page refresh to be recalculated and eventually removed.

The discount plugin seems to add all the necessary data with these hooks

    // Prepare cart discounts
    add_action('woocommerce_before_calculate_totals', array($this, 'prepare_cart_discounts'), 1);

    // Apply cart discounts
    add_action('woocommerce_after_calculate_totals', array($this, 'apply'));

    // Remove no longer applicable cart discounts
    add_action('woocommerce_before_calculate_totals', array($this, 'remove_cart_discounts'), 2);
    add_action('woocommerce_check_cart_items', array($this, 'remove_cart_discounts'), 1);

    // Invalidate no longer applicable cart discounts
    add_filter('woocommerce_coupon_is_valid', array($this, 'maybe_invalidate_cart_discount'), 10, 2);

    // Register custom coupon type
    add_filter('woocommerce_coupon_discount_types', array($this, 'register_custom_coupon_type'));
Mike 2 months 0 Answers 18 views 0

Leave an answer