【问题标题】:WooCommerce - Hide other shipping methods when FREE SHIPPING is availableWooCommerce - 当免费送货可用时隐藏其他送货方式
【发布时间】:2016-11-11 20:18:39
【问题描述】:

当 Woocommerce 提供免费送货服务时,我想隐藏其他送货选项。

因为即使有免费送货选项,现在最新版本的 woocommerce 仍然显示其他送货选项。

请帮忙

【问题讨论】:

    标签: php wordpress woocommerce shipping shipping-method


    【解决方案1】:

    WooCommerce 2.6+ 有这个最近的代码 sn-p。你可以使用:

    add_filter( 'woocommerce_package_rates', 'hide_other_shipping_when_free_is_available', 100, 2 );
    
    function hide_other_shipping_when_free_is_available( $rates, $package ) {
    
        $free = array();
        foreach ( $rates as $rate_id => $rate ) {
            if ( 'free_shipping' === $rate->method_id ) {
                $free[ $rate_id ] = $rate;
                break;
            }
        }
        return ! empty( $free ) ? $free : $rates;
    }
    

    您需要刷新运输缓存数据:在woocommerce运输设置中禁用、保存和启用、保存当前运输区域的相关运输方式。


    对于 WooCommerce 2.5,您应该试试这个:

    add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
    
    function hide_shipping_when_free_is_available( $rates, $package ) {
        
        // Only modify rates if free_shipping is present
        if ( isset( $rates['free_shipping'] ) ) {
        
            // To unset a single rate/method, do the following. This example unsets flat_rate shipping
            unset( $rates['flat_rate'] );
            
            // To unset all methods except for free_shipping, do the following
            $free_shipping          = $rates['free_shipping'];
            $rates                  = array();
            $rates['free_shipping'] = $free_shipping;
        }
        
        return $rates;
    }
    

    将此代码粘贴到位于活动子主题或主题中的 function.php 文件中。


    参考:Hide other shipping methods when FREE SHIPPING is available (official doc)

    相关:

    【讨论】:

    • 我应该在哪里调用这个函数?
    • 我会像这样调用这个函数 add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );在function.php上? @LoicTheAztec
    • 你不需要调用它……只需将所有的 sn-p 粘贴到你的活动主题的 function.php 文件中……这将完成这项工作。为什么?因为此功能与 woocommerce 核心中的 woocommerce_package_rates 挂钩……请参阅:Hooks: Action and Filter reference
    • 建议将其转换为插件或site specific snippets plugin,这样它就不会与主题相关联。但这绝对是 WC2.6 代码,因为这是 Woo 开发人员在他们的 gist 中建议的
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2020-06-22
    • 2015-08-14
    • 2019-05-31
    • 2020-11-05
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多