2017-05-10 52 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每个车项目......

相关问题