2
votes

what I am trying to achive is if user adds a particual product in cart its price should change to zero

Here is the simple code snippet which I am using to update cart item price but

add_action('woocommerce_before_calculate_totals','set_bonus_product_pice');
function set_bonus_product_pice($cart_object){
     if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;

       $free_product_ID = 10;
       foreach ( $cart_object->cart_contents as $key=>$cart_item) { 
           if($cart_item['product_id'] == $free_product_ID){
                 $cart_item['data']->set_price(0);
                 break;
           }
        }
 }

Woocommerce version is 4.3

In above code it goes inside if condition also set price is called properly and calling set price sets new price under change key of product object, on further dubugging it works fine until wc_get_price_excluding_tax method is called in class-wc-cart.php file , some how wc_get_price_excluding_tax method removes the change from product object.

Also I tried various variations of it like instead of using $cart_object directly I used $woocommerce->get_cart(). The same solution has worked for me previously but not sure if its due to some change in latest version of woocommerce

1
is your product type is simple?Bhautik
yes it a simple product with virtual type, no tax classes or any other option is applied,also I already tried $value['data']->price = $custom_price; this used to work for woocommerce before 3.2Swapnil Ghone
check my below answer.Bhautik

1 Answers

0
votes

change $cart_item['data']->set_price(0); to $value['data']->price = $custom_price;

check below code.

add_action( 'woocommerce_before_calculate_totals', 'set_bonus_product_pice', 20, 1 );
function set_bonus_product_pice( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $custom_price    = 10; // This will be your custome price  
    $free_product_ID = 10;
    
    foreach ( $cart_object->get_cart() as $item ) {
        if ( $item['product_id'] == $free_product_ID ) {
            $item['data']->set_price( $custom_price );
        }
    }
}