• So basically, I’m applying discounts when certain product combinations are met.

    I’m just using acf to add custom fields to products. Certain products have accessories, and when that product and that accessory are in the cart, the accessory gets a discount applied.

    This works, but when I refresh the cart or go to the checkout screen or whatever, it all just goes back to default. What am I doing wrong?

    My code is below, albeit a little useless without the set up I have.

    function add_discount_to_accessories( $cart_object) {
    
        $prod_accs = '';
    
       foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_id   = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
    
                $foundAccessories = get_field('product_accessories', $product_id);
    
                    if ($foundAccessories)  {
    
                    $post_objects = get_field('accessories', $product_id);
    
                        if( $post_objects ) {
    
                            foreach( $post_objects as $poster) {
                                    $prod_accs[] = $poster->ID;
                            }
    
                        }
                    }
        }
        if ($prod_accs != '') {
    
            foreach ( $cart_object->cart_contents as $key => $value ) {   
    
                 $_product = apply_filters( 'woocommerce_cart_item_product', $value['data'], $value, $key );
    
                foreach($prod_accs as $prod) {
    
                    $doIt = false;
    
                    if ($_product->id == $prod) {
                        $doIt = true;
                    }
    
                    if (!$doIt) {
                        $children = $_product->get_children();
    
                        if (count($children) > 0) {
                            foreach ($children as $child) {
                                  if ($_product->id == $child) {
                                    $doIt = true;
                                  }
                            }
                        }
                    }
    
                    if ($doIt) {
                        $oldPrice = $value['data']->price;
                        $value['data']->price = $oldPrice - ($oldPrice/100 * 20);
                       // $value['data']->setPrice($oldPrice - ($oldPrice/100 * 20));
                        $cart_object->persistent_cart_update();
    
                    }
    
                }
            }
    
        }
    
    }
    
    add_action( 'woocommerce_before_calculate_totals', 'add_discount_to_accessories', 1, 1 );

    https://wordpress.org/plugins/woocommerce/

  • The topic ‘woocommerce_before_calculate_totals not sticking’ is closed to new replies.