2017-04-07 120 views
4

我已经从2.6.14更新到WC 3.0.1。
我原来的代码如下:woocommerce_before_calculate_totals在更新到WC 3.0.1后停止工作

add_action('woocommerce_before_calculate_totals', 'add_custom_price'); 

function add_custom_price($cart_object) { 
    $custom_price = 10; // This will be your custome price 
    foreach ($cart_object->cart_contents as $key => $value) { 
     $value['data']->price = $custom_price; 
    } 
} 

它不再更新的购物车或minicart的价格。

+0

您不能再直接访问'$ product'属性。如果启用了“WP_DEBUG”,您应该在'debug.log'中看到关于此的警告。您现在必须使用setter和getters来获得产品,订单,订单商品和优惠券对象。 – helgatheviking

+0

感谢helgatheviking, 您能否提供一个获取和设置产品价格的例子? –

+1

查看[source]中的'set_price()'(https://github.com/woocommerce/woocommerce/blob/3.0.0/includes/abstracts/abstract-wc-product.php#L804-L806) – helgatheviking

回答

7

为了在Woocommerce(3.0.1)的最新版本中推翻购物车上的产品价格,请尝试在woocommerce中使用set_price($ price)函数,这将有所帮助。 Source here

add_action('woocommerce_before_calculate_totals', 'woocommerce_pj_update_price', 99); 

function woocommerce_pj_update_price() { 

    $custom_price = $_COOKIE["donation"]; // This will be your custom price 
    $target_product_id = 413; //Product ID 

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { 

     if($cart_item['data']->get_id() == $target_product_id){ 

      $cart_item['data']->set_price($custom_price); 
     } 

    } 

} 
+1

我浪费了3个小时,寻找解决方案。感谢你不是3天... –

+1

大声笑。很高兴我帮助了@CarlosFaria! –

0

工程用少许变化:

//OLD: 
$value['data']->price = $custom_price; 

//NEW: 
$value['data']->set_price($custom_price); 

function add_custom_price($cart_object) { 
    $custom_price = 10; // This will be your custome price 
    foreach ($cart_object->cart_contents as $key => $value) { 
     $value['data']->set_price($custom_price); 
    } 
} 
0
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 10, 1); 
function add_custom_price($cart_obj) { 

    // This is necessary for WC 3.0+ 
    if (is_admin() && ! defined('DOING_AJAX')) 
     return; 

    foreach ($cart_obj->get_cart() as $key => $value) { 
     $value['data']->set_price(40); 
    } 
} 

如果我设置$值[ '数据'] - > set_price(40)正常工作,但:

foreach ($cart_obj->get_cart() as $key => $value) { 
      $price = 50; 
      $value['data']->set_price($price); 
}