Woocommerce - 如果免费送货无法正常工作,则隐藏其他送货方式

问题描述 投票:0回答:1

当免费送货被激活时,我试图隐藏其他送货方式,但当我添加两种不同的产品时,它会支持所有可能的送货方式,而不仅仅是免费送货。

当我添加超过 50 欧元的产品时,它运行良好,但当我添加超过一种产品时,它不起作用。

add_filter( 'woocommerce_package_rates', 'cssigniter_hide_other_methods_when_free_shipping_is_available', 100 );
function cssigniter_hide_other_methods_when_free_shipping_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;
}
php wordpress woocommerce hook
1个回答
0
投票

当免费送货可用时,您的代码似乎正确地过滤了其他送货方式,但当购物车中有多个产品时,就会出现问题。

看看这个替代方案:


    add_filter( 'woocommerce_package_rates', 'cssigniter_hide_other_methods_when_free_shipping_is_available', 100 );
    function cssigniter_hide_other_methods_when_free_shipping_is_available( $rates ) {
        $is_free_shipping_available = false;
        foreach ( $rates as $rate ) {
            if ( 'free_shipping' === $rate->method_id ) {
                $is_free_shipping_available = true;
                break;
            }
        }
    
        if ( $is_free_shipping_available ) {
            $cart_subtotal = WC()->cart->subtotal;
            $free_shipping_threshold = 50; // Adjust this value as needed
    
           if ( $cart_subtotal >= $free_shipping_threshold ) {
                $free = array();
                foreach ( $rates as $rate_id => $rate ) {
                    if ( 'free_shipping' === $rate->method_id ) {
                        $free[ $rate_id ] = $rate;
                        break;
                    }
                }
                return ! empty( $free ) ? $free : $rates;
            }
        }
    
        return $rates;
    }

此代码将首先检查是否可以免费送货。如果是,它将检查购物车小计是否高于阈值。如果两个条件都满足,则只保留包邮方式;否则,它将返回所有可用的运费。 确保根据您自己的需要使用 $free_shipping_threshold 变量。

LMK 如果这有帮助的话。

© www.soinside.com 2019 - 2024. All rights reserved.