2017-08-13 111 views
2
值數

我想指定2個不同的統一費率的運輸方式的成本,而無需使用插件:基於屬性變扁率的運輸成本在WooCommerce

  • 如果在車產品僅一個供應商,統一費率運輸成本需要19英鎊。
  • 如果購物車中有多個商品來自多個供應商,則統一費率運費需要爲39英鎊。

我已經嘗試了各種插件,但他們專注於基於尺寸,重量,數量,位置,類別的運費,而不是屬性或術語。

我有一個屬性名爲供應商 8條款。每個術語是不同的供應商/供應商。

這裏的PHP邏輯的類型,我想實現:

if product attribute term quantity = 1 

then flat rate = £19 

else 

if product attribute term quantity > 1 

then flat rate = £39 

我怎樣才能改變這種「扁平率」的送貨方式費用時,有超過1個屬性供應商方面的車?

回答

3

這一過程需要2步:一些代碼和一些設置...

1)代碼 - 您可以使用woocommerce_package_rates過濾鉤子鉤住一個自定義功能,當車項目是針對「固定費率」航運法從1個多供應商:

add_filter('woocommerce_package_rates', 'custom_flat_rate_cost_calculation', 10, 2); 
function custom_flat_rate_cost_calculation($rates, $package) 
{ 

    // SET BELOW your attribute slug… always begins by "pa_" 
    $attribute_slug = 'pa_vendor'; // (like for "Color" attribute the slug is "pa_color") 


    // Iterating through each cart item to get the number of different vendors 
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { 

     // The attribute value for the current cart item 
     $attr_value = $cart_item[ 'data' ]->get_attribute($attribute_slug); 

     // We store the values in an array: Each different value will be stored only one time 
     $attribute_values[ $attr_value ] = $attr_value; 
    } 
    // We count the "different" attribute values stored 
    $count = count($attribute_values); 

    // Iterating through each shipping rate 
    foreach($rates as $rate_key => $rate_values){ 
     $method_id = $rate_values->method_id; 
     $rate_id = $rate_values->id; 

     // Targeting "Flat Rate" shipping method 
     if ('flat_rate' === $method_id) { 
      // For more than 1 vendor (count) 
      if($count > 1){ 
       // Get the original rate cost 
       $orig_cost = $rates[$rate_id]->cost; 
       // Calculate the new rate cost 
       $new_cost = $orig_cost + 20; // 19 + 20 = 39 
       // Set the new rate cost 
       $rates[$rate_id]->cost = $new_cost; 
       // Calculate the conversion rate (for below taxes) 
       $conversion_rate = $new_cost/$orig_cost; 
       // Taxes rate cost (if enabled) 
       foreach ($rates[$rate_id]->taxes as $key => $tax){ 
        if($rates[$rate_id]->taxes[$key] > 0){ 
         $new_tax_cost = number_format($rates[$rate_id]->taxes[$key]*$conversion_rate, 2); 
         $rates[$rate_id]->taxes[$key] = $new_tax_cost; // set the cost 
        } 
       } 
      } 
     } 
    } 
    return $rates; 
} 

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

該代碼與woocommerce版本測試3+和工作

2)設置, - 一旦上面的代碼已經被保存在您的活動主題的function.php文件,你將需要設置(對於您所有的運輸區域)「統一費率」運輸方式的費用爲19(£19)(並保存)。

重要:要刷新配送方式緩存,你需要禁用「扁平率」則保存,並使背部「扁平率」則保存

現在,這應該適合您的預期。

+0

完美地工作。那是@LoicTheAztec - 非常感謝。 –