如果购物车中有超过 15 件商品。如何强制只使用一种所需的运输方式(即 DHL)并隐藏所有其他运输方式?
我已经有了“灵活运输”插件,但更喜欢functions.php中的钩子。
如果购物车中有超过 15 件商品。如何强制只使用一种所需的运输方式(即 DHL)并隐藏所有其他运输方式?
我已经有了“灵活运输”插件,但更喜欢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 文件中。测试和工作。
刷新运输缓存:( 必需)
- 此代码已保存在活动主题的 function.php 文件中。
- 购物车是空的
- 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
你已经完成了,你可以测试它。