【发布时间】:2020-12-25 18:40:41
【问题描述】:
来自Disable specific shipping method if a cart item uses a specific shipping class ID的回答代码,如果购物车中的另一个商品没有该运输类别ID,并且想根据产品运输类别再次显示flat_rate:2,该怎么办?
【问题讨论】:
标签: php wordpress woocommerce cart shipping-method
来自Disable specific shipping method if a cart item uses a specific shipping class ID的回答代码,如果购物车中的另一个商品没有该运输类别ID,并且想根据产品运输类别再次显示flat_rate:2,该怎么办?
【问题讨论】:
标签: php wordpress woocommerce cart shipping-method
您将改用以下内容:
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 10, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
$found = $others = false; // Initializing
$shipping_class_id = 513; // <== ID OF YOUR SHIPPING_CLASS
$shipping_rate_id = 'flat_rate:2'; // <== Targeted shipping rate ID
// Checking cart items for current package
foreach( $package['contents'] as $key => $cart_item ) {
$product = $cart_item['data']; // The WC_Product Object
if( $product->get_shipping_class_id() == $shipping_class_id ) {
$found = true;
} else {
$others = true;
}
}
if( $found && ! $others && isset($rates[$shipping_rate_id]) ) {
unset($rates[$shipping_rate_id]); // Removing specific shipping method
}
return $rates;
}
代码在您的活动子主题(或活动主题)的functions.php 文件中。它应该可以工作。
刷新运输缓存:
- 此代码已保存在您的 functions.php 文件中。
- 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
您已完成,您可以对其进行测试。
【讨论】: