简体   繁体   English

woocommerce_after_calculate_totals 无法更新购物车商品价格

[英]woocommerce_after_calculate_totals not working to update cart item price

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 Woocommerce 版本是 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.在上面的代码中,如果条件也设置价格被正确调用并且调用 set price 在产品对象的更改键下设置新价格,它会进入内部,进一步调试它可以正常工作,直到在 class-wc-cart.php 文件中调用 wc_get_price_ exclude_tax 方法,一些wc_get_price_ exclude_tax 方法如何从产品对象中删除更改。

Also I tried various variations of it like instead of using $cart_object directly I used $woocommerce->get_cart().我还尝试了它的各种变体,例如我使用 $woocommerce->get_cart() 而不是直接使用 $cart_object。 The same solution has worked for me previously but not sure if its due to some change in latest version of woocommerce相同的解决方案以前对我有用,但不确定是否由于最新版本的 woocommerce 发生了一些变化

change $cart_item['data']->set_price(0);更改 $cart_item['data']->set_price(0); to $value['data']->price = $custom_price;到 $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 );
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM