隐藏WooCommerce中特定运输类别的运输方法 [英] Hide shipping methods for specific shipping class in WooCommerce
问题描述
基本上,当存在具有运输类别"Roller"(ID 92
)的购物车商品时,我想尝试使统一费率方法ID flat_rate:7
已禁用.
Essentially I'm trying to make the flat rate method Id flat_rate:7
disabled when there is cart items that have the shipping class "Roller" (ID 92
).
这是我尝试的代码:
add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 10, 2);
function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
$hide_when_shipping_class_exist = array(
92 => array(
'flat_rate:7'
)
);
$shipping_class_in_cart = array();
foreach(WC()->cart->cart_contents as $key => $values) {
$shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}
foreach($hide_when_shipping_class_exist as $class_id => $methods) {
if(in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
return $available_shipping_methods;
}
运输类别ID 92
是运输类别,我要为其隐藏flat_rate:7
.
我的网站是这样的: http://www.minimoto.me/ WordPress:4.8.4 WooCommerce:3.1.1
My Site is this: http://www.minimoto.me/ WordPress: 4.8.4 WooCommerce: 3.1.1
任何帮助将不胜感激.
推荐答案
更新2019:您应该尝试使用这种更短,更紧凑,更有效的方法:
Update 2019: You should try instead this shorter, compact and effective way:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE define your shipping class to find
$class = 92;
// HERE define the shipping method to hide
$method_key_id = 'flat_rate:7';
// Checking in cart items
foreach( $package['contents'] as $item ){
// If we find the shipping class
if( $item['data']->get_shipping_class_id() == $class ){
unset($rates[$method_key_id]); // Remove the targeted method
break; // Stop the loop
}
}
return $rates;
}
代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.
经过测试,可以正常工作.
Tested and works.
有时候,您可能需要刷新前往送货地区的送货方式,然后禁用/保存并重新启用/保存您的固定费率"送货方式.
Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your "flat rates" shipping methods.