Woocommerce更新价格不能保存在购物车会话中


Woocommerce Update Price Doesn't Save In Cart Session

我在Wordpress Woocommerce中遇到了问题,我已经根据他们需要的任何条件以编程方式更新了产品的价格。下面是一个简单的例子。我有它显示,然后添加到购物车就好了。我的问题是,当用户退出并重新登录时,购物车最终会返回产品的全部价格。要么是我更新的价格不正确,要么是有更好的方法来确保购物车有正确的折扣价格。

这是我在functions。php

中的内容
  add_action('woocommerce_get_price_html','pricechanger');  
  function pricechanger($price){
      $theid = get_the_ID();
      $product = wc_get_product($theid);
      $price = $product->price;
      $price = //do something to the price here
      //save the productid/price in session for cart
      $_SESSION['pd']['$theid'] = $price;
      add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10, 2);
      add_action( 'init', 'woocommerce_add_to_cart_action', 10);
      add_action( 'init', 'woocommerce_checkout_action', 10 );
      return $price;
  }

因为价格不会转换到添加到购物车按钮,所以我不得不在会话中保存它们。我还没有找到任何地方可以把价格发送到购物车。

add_action( 'woocommerce_before_calculate_totals', 'woo_add_discount');
function woo_add_discount() {
    if(isset($_SESSION['pd'])) {   
     foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      foreach($_SESSION['pd'] as $key => $val) {
        if($cart_item['data']->id == $key){
            $cart_item['data']->set_price($val);
        }
       }
     }
    } 
}

非常感谢帮助!谢谢!

我忘记在这里发布我的总结答案了。

你需要运行这些钩子对你的价格变化代码:

add_action( 'woocommerce_before_calculate_totals', 'your_function_here');
add_action( 'woocommerce_before_mini_cart', 'your_function_here');
function your_function_here(){
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { 
       //do something to your price here
       $price = 'some calculation here';
       //set your price
       $cart_item['data']->price = floatval($price);
    }
}

希望这对某人有所帮助!