woocommerce 根据数量有条件地隐藏运输方式
woocommerce hide shipping methods conditionally on number
如果购物车中的商品超过 15 件。我如何才能强制只使用一种所需的运输方式(即 DHL)并隐藏所有其他运输方式?
我已经有了插件 "flexible shipping" 但更喜欢 functions.php 中的挂钩。
如果购物车中的商品超过 15 件,以下将仅启用一种已定义的送货方式:
add_filter( 'woocommerce_package_rates', 'hide_shipping_methods_based_on_item_count', 10, 2 );
function hide_shipping_methods_based_on_item_count( $rates, $package ) {
// HERE the targeted shipping method ID (see the attribute "value" of the related shipping method input field)
$targeted_method_id = 'flat_rate:12'; // <== Replace with your DHL shipping method ID
// HERE the articles count threshold
$more_than = 15;
// Cart items count
$item_count = WC()->cart->get_cart_contents_count();
if( WC()->cart->get_cart_contents_count() > $more_than ) {
foreach ( $rates as $rate_key => $rate ) {
if ( $rate->id != $targeted_method_id ) {
unset($rates[$rate_key]);
}
}
}
return $rates;
}
代码在您的活动子主题(或主题)的 function.php 文件中。已测试并有效。
Refresh the shipping caches: (required)
- This code is already saved on your active theme's function.php file.
- The cart is empty
- In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.
如果购物车中的商品超过 15 件。我如何才能强制只使用一种所需的运输方式(即 DHL)并隐藏所有其他运输方式?
我已经有了插件 "flexible shipping" 但更喜欢 functions.php 中的挂钩。
如果购物车中的商品超过 15 件,以下将仅启用一种已定义的送货方式:
add_filter( 'woocommerce_package_rates', 'hide_shipping_methods_based_on_item_count', 10, 2 );
function hide_shipping_methods_based_on_item_count( $rates, $package ) {
// HERE the targeted shipping method ID (see the attribute "value" of the related shipping method input field)
$targeted_method_id = 'flat_rate:12'; // <== Replace with your DHL shipping method ID
// HERE the articles count threshold
$more_than = 15;
// Cart items count
$item_count = WC()->cart->get_cart_contents_count();
if( WC()->cart->get_cart_contents_count() > $more_than ) {
foreach ( $rates as $rate_key => $rate ) {
if ( $rate->id != $targeted_method_id ) {
unset($rates[$rate_key]);
}
}
}
return $rates;
}
代码在您的活动子主题(或主题)的 function.php 文件中。已测试并有效。
Refresh the shipping caches: (required)
- This code is already saved on your active theme's function.php file.
- The cart is empty
- In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.