Php 您可以根据数量有条件地隐藏装运方式

Php 您可以根据数量有条件地隐藏装运方式,php,wordpress,woocommerce,cart,shipping-method,Php,Wordpress,Woocommerce,Cart,Shipping Method,如果购物车中的物品超过15件。我如何只强制一种所需的运输方式(即DHL)并隐藏所有其他运输方式 我已经有了“flexible shipping”插件,但更喜欢functions.php中的钩子。如果购物车中有超过15篇文章,则以下将只启用一种已定义的配送方法: add_filter( 'woocommerce_package_rates', 'hide_shipping_methods_based_on_item_count', 10, 2 ); function hide_shipping_m

如果购物车中的物品超过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;
}
add_filter('woocommerce_package_rates'、'hide_shipping_methods_基于_item_count'、10、2);
函数hide\u shipping\u methods\u基于项目计数($rates,$package){
//这里是目标装运方法ID(请参见相关装运方法输入字段的属性“值”)
$targeted_method_id='flat_rate:12';//购物车->获取购物车内容计数();
如果(WC()->cart->get_cart\u contents\u count()>$more\u than){
foreach($rate作为$rate\u key=>$rate的费率){
如果($rate->id!=$targeted\u method\u id){
未设置($rates[$rate_key]);
}
}
}
返回美元汇率;
}
代码位于活动子主题(或主题)的function.php文件中。测试和工作

刷新装运缓存:(必需)

  • 此代码已保存在活动主题的function.php文件中
  • 车是空的
  • 在配送区域设置中,禁用/保存任何配送方法,然后启用“返回/保存”
  • 您已经完成了,您可以进行测试


    非常感谢你,洛伊奇。我们有几个航运区。您的代码如何通过其名称(“第一类”)而不是其实例id修改为以装运方式为目标?@cysus您可以尝试使用
    $rate->label
    而不是
    $rate->id
    …如果您喜欢/想要,请回答,谢谢。