【问题标题】:WooCommerce: Hide other shipping methods except local pickup when free shipping is availableWooCommerce:当免费送货可用时,隐藏除本地取货外的其他送货方式
【发布时间】:2021-05-29 17:11:34
【问题描述】:

当提供免费送货服务时,我不想隐藏本地取货。删除本地取货没有任何意义,但我不知道如何使用官方代码不删除它。

/**
 * Hide shipping rates when free shipping is available.
 * Updated to support WooCommerce 2.6 Shipping Zones.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 */
function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

这是我删除 flat_rate1 的尝试,因为对我来说,这是付费选项。同样,我想保持免费送货和本地取货。

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

【问题讨论】:

    标签: php arrays wordpress woocommerce shipping-method


    【解决方案1】:

    要隐藏除本地取货和免费送货方式以外的所有送货方式,请使用以下命令:

    add_filter( 'woocommerce_package_rates', 'hide_shipping_except_local_when_free_is_available', 100 );
    function hide_shipping_except_local_when_free_is_available($rates) {
        $free = $local = array();
    
        foreach ( $rates as $rate_id => $rate ) {
            if ( 'free_shipping' === $rate->method_id ) {
                $free[ $rate_id ] = $rate;
            } elseif ( 'local_pickup' === $rate->method_id ) {
                $local[ $rate_id ] = $rate;
            }
        }
        return ! empty( $free ) ? array_merge( $free, $local ) : $rates;
    }
    

    代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    相关:

    【讨论】:

    • 谢谢。看了你的其他功能,我明白了很多。
    猜你喜欢
    • 2016-11-11
    • 1970-01-01
    • 2020-06-22
    • 2019-05-31
    • 2015-08-14
    • 2014-01-06
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多