Woocommerce 4.7 update price in ‘woocommerce_before_calculate_totals’

Question

I create a plugin to create fields in the .cart form for products.

Some fields are paid options.

So far everything worked. The prices of the options are added to the price of the product in the cart.

I use the ‘woocommerce_before_calculate_totals’ hook.

Unfortunately the last field I put, "afg-put-in-box", doesn’t update the price each time.

This option contains an array of product ids.

function beforeCalculateTotals( $cart_obj ) {
            if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
            $cart = $cart_obj->get_cart();
            foreach($cart as $key => $value ) {
                if(isset($value['afg-original-price'])) :

                    $price = str_replace(',','.',$value['afg-original-price']);

                    foreach($value as $subKey => $subValue) {
                        if (strpos($subKey, 'afg-textarea-field-price-') !== false ) {
                            $price += str_replace(',','.',$subValue);
                            $value['data']->set_price($price);
                        }
                    }

                    foreach($value as $subKey => $subValue) {
                        if (strpos($subKey, 'afg-finition-price-') !== false ) {
                            $price += str_replace(',','.',$subValue);
                            $value['data']->set_price($price);
                        }     
                    }

                    foreach($value as $subKey => $subValue) {
                        if (strpos($subKey, 'afg-color-price-') !== false ) {
                            $price += str_replace(',','.',$subValue);
                            $value['data']->set_price($price);
                        }     
                    }

                    foreach($value as $subKey => $subValue) {
                        if(strpos($subKey, 'afg-put-in-box') !== false ) {
                            $productIds = $subValue;
                            foreach ($productIds as $productId) {
                                $product = wc_get_product($productId);
                                $price += str_replace(',','.',$product->get_price());
                            }
                            $value['data']->set_price($price);
                        }
                    }   

                endif;
            }
                
        }
add_action( 'woocommerce_before_calculate_totals', beforeCalculateTotals', 99, 1 );

Strangely the field "afg-put-in-box" is taken into account only when one of the other options is filled, then the total price is correctly calculated.

Also for the other options to work I have to call set_price for each option.

Could someone please explain to me what I am doing wrong?

Thank you very much for your time.

0
Cedric 2 months 0 Answers 8 views 0

Leave an answer