微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有条件地隐藏WooCommerce中的运输方式

如何解决有条件地隐藏WooCommerce中的运输方式

当所选的运送国家是美国时,我试图在WooCommerce的结帐页面上隐藏一种运送方式-'US'并且cart_total超过100。但是当它只应隐藏正常运输(flat_rate:4)。任何帮助将不胜感激!

function nd_hide_shipping_when_free_is_available( $rates ) {
    $shipping_counrtry = WC()->customer->get_shipping_country();
    $total = WC()->cart->get_displayed_subtotal();
    if ($shipping_country == "US" && $total >= 100){
        unset($rates['flat_rate:4']);
        return $rates;
    }else{
        $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','nd_hide_shipping_when_free_is_available',100 );

解决方法

您可以尝试以下操作,这将隐藏美国的'flat_rate:4'送货方式费率ID,并且当购物车小计达到100或更多时,否则,当免费送货时,它将隐藏其他送货方式:

add_filter( 'woocommerce_package_rates','shipping_based_on_country_subtotal_and_free_available',100,2 );
function shipping_based_on_country_subtotal_and_free_available( $rates,$package ) {
    $country   = WC()->customer->get_shipping_country();
    $subtotal  = WC()->cart->subtotal; // subtotal incl taxes
    $condition = $country == "US" && $subtotal >= 100; // <== HERE Set your condition (country and minimal subtotal amount)
    $free      = array(); // Initializing

    // Loop through shipping rates for current shipping package
    foreach ( $rates as $rate_key => $rate ) {
        if ( $condition ){
            $targeted_rate_id = 'flat_rate:4';
            
            if( $targeted_rate_id === $rate_key ) {
                unset($rates[$targeted_rate_id]);
            }
        }
        elseif ( 'free_shipping' === $rate->method_id ) {
            $free[$rate_key] = $rate;
        }
    }
    return ! empty( $free ) && ! $condition ? $free : $rates;
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。

重要提示:保存代码后,清空购物车以刷新运费...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?