2016-08-13 45 views
1

Based on this answer (code below),我成功地可以隐藏特定产品类别本地传递选项扁平率可用。这是完美的。配送方式 - 本地拾取选项不可用时,扁平率是隐藏

问题:对于该特定类别,本地取件选项不可用

如何使本地皮卡选项可用于此特殊类别?

这是我使用的代码:

function custom_shipping_methods($rates){ 

    // Define/replace here your correct category slug (!) 
    $cat_slug = 'your_category_slug'; 
    $prod_cat = false; 

    // Going through each item in cart to see if there is anyone of your category   
    foreach (WC()->cart->get_cart() as $values) { 
     $item = $values['data']; 

     if (has_term($cat_slug, 'product_cat', $item->id)) 
      $prod_cat = true; 
    } 

    $rates_arr = array(); 

    if ($prod_cat) { 
     foreach($rates as $key => $rate) { 
      if ('free_shipping' === $rate->method_id || 'local_pickup' === $rate->method_id || 'local_delivery' === $rate->method_id) { 
       $rates_arr[ $rate_id ] = $rate; 
       break; 
      } 
     } 
    } 
    return !empty($rates_arr) ? $rates_arr : $rates; 
} 
add_filter('woocommerce_package_rates', 'custom_shipping_methods', 100); 

一件事:有没有可能显示本地传递并根据位置特殊类别本地拾取

当前在我的店铺本地取货送货仅适用于一个位置。

回答

1

建议:只为WooCommerce版本2.6.x的(对于WC增加兼容性3+)

许多测试...你需要改变你的代码2的小东西后:

add_filter('woocommerce_package_rates', 'custom_shipping_methods', 100, 2); 
function custom_shipping_methods($rates, $package){ 

    // Define/replace here your correct category slug (!) 
    $cat_slug = 'posters'; 
    $prod_cat = false; 

    // Going through each item in cart to see if there is anyone of your category 
    foreach (WC()->cart->get_cart() as $values) { 
     $product = $values['data']; 

     // compatibility with WC +3 
     $product_id = method_exists($product, 'get_id') ? $product->get_id() : $product->id; 

     if (has_term($cat_slug, 'product_cat', $product_id)) 
      $prod_cat = true; 
    } 

    $rates_arr = array(); 

    if ($prod_cat) { 
     foreach($rates as $rate_id => $rate) { // <== There was a mistake here 

      if ('free_shipping' === $rate->method_id || 'local_pickup' === $rate->method_id || 'local_delivery' === $rate->method_id) { 
       $rates_arr[ $rate_id ] = $rate; 
       // break; // <========= Removed this to avoid stoping the loop 
      } 
     } 
    } 
    return !empty($rates_arr) ? $rates_arr : $rates; 
} 

有2个失误:

  • 一个在foreach循环中用一个坏的变量名替换它。
  • 删除break;避免在一个条件匹配时停止foreach循环。

这一代码进入你的活动的子主题或主题的function.php文件。

此代码经过测试,功能齐全(如果你设置了正确的航运区,将工作)

您将需要刷新航运缓存数据:关闭,保存并启用,保存当前航运区相关的运输方式,在woocommerce送货设置。


参考文献:

+0

大。非常感谢你。它的工作完美:) –

+0

@ZahidIqbal有一个愚蠢的错误和'突破;'...见你周围:) ... – LoicTheAztec