繁体   English   中英

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

[英]woocommerce_after_calculate_totals not working to update cart item price

我想要实现的是,如果用户在购物车中添加特定产品,其价格应更改为零

这是我用来更新购物车商品价格的简单代码片段,但是

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 版本是 4.3

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

我还尝试了它的各种变体,例如我使用 $woocommerce->get_cart() 而不是直接使用 $cart_object。 相同的解决方案以前对我有用,但不确定是否由于最新版本的 woocommerce 发生了一些变化

更改 $cart_item['data']->set_price(0); 到 $value['data']->price = $custom_price;

检查下面的代码。

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