2017-04-07 78 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); 
} 
相關問題