簡體   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