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);
还有一件事:是否可以根据位置显示该特殊类别的本地交付和本地提货?
目前在我的商店本地提货或交付仅针对一个地点设置。
答案 0 :(得分:1)
建议: 仅适用于WooCommerce版本2.6.x(增加了WC 3 +的兼容性)
经过多次测试......您需要在代码中更改两件小事:
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个错误:
break;
,避免在一个条件匹配时停止foreach循环。此代码位于您的活动子主题或主题的function.php文件中。
此代码已经过测试并且功能齐全 (如果您正确设置了送货区域,它将会正常工作)。
您需要刷新送货缓存数据:禁用,保存并启用,保存当前送货区域的相关送货方式,在woocommerce送货设置中。
参考文献: