dongqiyou0303 2016-06-24 21:05
浏览 40
已采纳

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

I'm having issues in Wordpress Woocommerce whereby I have programmatically updated prices of products based on whatever conditions they need. Below is a simple example. I have it displaying and then adding to the cart just fine. My problem is, when the user logs out and logs back in, the cart ends up returning the full prices of the product. Either I'm updating the price incorrectly, or there is a better way to ensure the cart has the correct discounted price.

Here is what I have in 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;

  }

Because the price wouldn't transition to the add to cart button, I've had to save them in a session. I haven't found anywhere that sends that price to the cart.

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);
        }
       }
     }
    } 

}

Help is greatly appreciated! Thanks!

  • 写回答

1条回答 默认 最新

  • douzhen1234 2017-02-24 22:50
    关注

    I forgot to post my concluded answer here.

    You need to run these hooks against your price change code:

    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);
    
        }
    
    }
    

    Hope that helps someone!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂