更新有多种方法可以做到这一点,而不需要任何 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' 替换为 'product_tag'
3) 如果您有一堆产品,您还可以创建运输类别并将其批量分配给您的产品。您需要在相关的运输方式中为其设置价格……
Filter Shipping method based on shipping class in Woocommerce 3
您应该需要刷新运输缓存:
1) 首先,此代码已保存在您的 function.php 文件中并清空您的购物车...
2) 在配送设置中,输入配送区域并禁用配送方式并“保存”。然后重新启用运送方式并“保存”。 你已经完成了。