Updated有多种方法可以做到这一点,而不需要 jQuery:
1)如果你的产品很少您可以使用以下代码,您将在其中定义:
代码:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product IDs in the array
$product_ids = array( 113, 115, 126 );
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('2846', '2851');
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( ! $found ) return $rates; // If not found we exit
// Loop through your active shipping methods
foreach( $rates as $rate_id => $rate ) {
// Remove all other shipping methods other than your defined shipping method
if ( in_array( $rate_id, $method_instances_ids ) ){
unset( $rates[$rate_id] );
}
}
return $rates;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并工作。
2)如果你有一堆产品,最好通过产品类别来定位这些产品(或产品标签)...您可以批量分配它。
在代码中,您将定义:
- 一个产品类别(或分类法为的产品标签
product_tag
)
- 要删除的运输方式实例 ID
代码:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product category in the array (ID, slug or name)
$terms = array( 'my-category' );
$taxonomy = 'product_cat';
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('2846', '2851');
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
$found = true;
break;
}
}
if ( ! $found ) return $rates; // If not found we exit
// Loop through your active shipping methods
foreach( $rates as $rate_id => $rate ) {
// Remove all other shipping methods other than your defined shipping method
if ( in_array( $rate_id, $method_instances_ids ) ){
unset( $rates[$rate_id] );
}
}
return $rates;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并工作。
为了让它发挥作用对于产品标签:
您只需替换分类法'product_cat'
by 'product_tag'
3)如果你有一堆产品,您还可以创建运输类别并将其批量分配给您的产品。您需要在相关的运输方式中设置价格......
根据 Woocommerce 3 中的运输类别过滤运输方法 https://stackoverflow.com/questions/49847171/filter-shipping-method-based-on-shipping-class-in-woocommerce-3/49847815#49847815
您应该需要刷新运输缓存:
1) 首先,此代码已保存在您的 function.php 文件中并清空您的购物车...
2) 在运输设置中,输入运输区域并禁用邮寄方式和“保存”。然后重新启用该功能邮寄方式和“保存”。你完成了。