Woocommerce_before_calculate_totals stopped working after upgrading to WC 3.0.1

I upgraded to WC 3.0.1 from version 2.6.14.
My source code is as follows:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' ); function add_custom_price( $cart_object ) { $custom_price = 10; // This will be your custome price foreach ( $cart_object->cart_contents as $key => $value ) { $value['data']->price = $custom_price; } } 

It no longer updates the price in the basket or minimap.

+5
woocommerce
source share
4 answers

To override the product price in the basket in the latest version of Woocommerce (3.0.1), try using the set_price ($ price) function in woocommerce, this will help. Source here

 add_action( 'woocommerce_before_calculate_totals', 'woocommerce_pj_update_price', 99 ); function woocommerce_pj_update_price() { $custom_price = $_COOKIE["donation"]; // This will be your custom price $target_product_id = 413; //Product ID foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { if($cart_item['data']->get_id() == $target_product_id){ $cart_item['data']->set_price($custom_price); } } } 
+8
source share

It works with a slight change:

 //OLD: $value['data']->price = $custom_price; //NEW: $value['data']->set_price( $custom_price ); function add_custom_price( $cart_object ) { $custom_price = 10; // This will be your custome price foreach ( $cart_object->cart_contents as $key => $value ) { $value['data']->set_price( $custom_price ); } } 
0
source share
 add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1); function add_custom_price( $cart_obj ) { // This is necessary for WC 3.0+ if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; foreach ( $cart_obj->get_cart() as $key => $value ) { $value['data']->set_price( 40 ); } } 

if I set $ value ['data'] → set_price (40), it works fine, but:

  foreach ( $cart_obj->get_cart() as $key => $value ) { $price = 50; $value['data']->set_price( $price ); } 
0
source share

The problem is that you name the price directly by $value['data']->price .
Do it:

 $value['data']->get_price() 

and I think your problem will be fixed

0
source share

All Articles