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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?