2017-05-10 60 views
2

我使用的是WooCommerce 3.0+,並且我在某個頁面上設置了產品價格。動態購物車項目定價不適用於WooCommerce 3.0+的訂單

 $regular_price = get_post_meta($_product->id, '_regular_price', true); 
     $buyback_percentage = get_post_meta($_product->id, '_goldpricelive_buy_back', true); 
     $fixed_amount = get_post_meta($_product->id, '_goldpricelive_fixed_amount', true); 
     $markedup_price = get_post_meta($_product->id, '_goldpricelive_markup', true); 
     $buyback_price = ($regular_price - $fixed_amount)/(1 + $markedup_price/100) * (1-$buyback_percentage/100); 
     $_product->set_price($buyback_price); 

價格正在更新我的車,但是當我點擊提交我的訂單,訂單的對象似乎沒有得到我定的價格。它需要原產品的價格。

有關我如何完成此任何想法?

感謝

+0

你怎麼調用所有這些代碼行? – Reigel

+0

我正在通過循環調用它 $ _product = wc_get_product($ id) – Elland

+0

好吧,'$ _product-> set_price($ buyback_price);''會爲'$ _product'的這個時刻設置價格。它不會保存。 – Reigel

回答

2

get_price()方法更新...

你應該使用這個自定義掛鉤函數內部woocommerce_before_calculate_totals行動掛鉤設置,你的產品ID或產品ID數組。
然後,對於他們中的每個人,您都可以進行自定義計算,以設置將在購物車,結帳和訂單提交後設置的自定義價格。

這裏是WooCommerce 3.0以上版本測試的功能代碼:

add_action('woocommerce_before_calculate_totals', 'adding_custom_price', 10, 1); 
function adding_custom_price($cart_obj) { 

    if (is_admin() && ! defined('DOING_AJAX')) 
     return; 

    // Set below your targeted individual products IDs or arrays of product IDs 
    $target_product_id = 53; 
    $target_product_ids_arr = array(22, 56, 81); 

    foreach ($cart_obj->get_cart() as $cart_item) { 
     // The corresponding product ID 
     $product_id = $cart_item['product_id']; 

     // For a single product ID 
     if($product_id == $target_product_id){ 
      // Custom calculation 
      $price = $cart_item['data']->get_price() + 50; 
      $cart_item['data']->set_price(floatval($price)); 
     } 

     // For an array of product IDs 
     elseif(in_array($product_id, $target_product_ids_arr)){ 
      // Custom calculation 
      $price = $cart_item['data']->get_price() + 30; 
      $cart_item['data']->set_price(floatval($price)); 
     } 
    } 
} 

代碼放在您的活動子主題(或主題)的function.php文件或也以任何插件文件。

然後你就可以很容易地通過您的產品動態值與同get_post_meta()函數替換我的假計算的固定值,就像在你的代碼,你有$product_id每個車項目......

相關問題