【问题标题】:woocommerce hide shipping methods conditionally on numberwoocommerce 根据数量隐藏运输方式
【发布时间】:2019-08-10 04:03:27
【问题描述】:

如果购物车中有超过 15 篇文章。如何仅强制使用一种所需的运输方式(即 DHL)并隐藏所有其他运输方式?

我已经有了“灵活运输”插件,但更喜欢functions.php中的钩子。

【问题讨论】:

    标签: php wordpress woocommerce cart shipping-method


    【解决方案1】:

    如果购物车中的商品超过 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 文件中。经过测试并且可以工作。

    刷新运输缓存: (必需)

    1. 此代码已保存在活动主题的 function.php 文件中。
    2. 购物车是空的
    3. 在配送区域设置中,禁用/保存任何配送方式,然后启用返回/保存。

    您已完成,您可以对其进行测试。

    【讨论】:

    • 非常感谢 Loic。我们有几个航运区。如何修改您的代码以通过其名称(“1st Class”)而不是其 instance_id 来定位运输方法?
    • @cysus 你可以尝试使用$rate-&gt;label 而不是$rate-&gt;id...如果你喜欢/想要你可以请upvote 回答,无论如何谢谢。
    猜你喜欢
    • 2014-07-05
    • 2014-08-06
    • 1970-01-01
    • 2021-01-08
    • 2021-12-08
    • 2020-08-25
    • 2018-07-10
    • 2021-11-22
    相关资源
    最近更新 更多