有条件地设置 Woocommerce 运输方式成本

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

如果购物车中的产品成本超过 99.99(含税),我将把一种运输方式成本设置为零,源代码可在此处

add_filter( 'woocommerce_package_rates', 'custom_shipping_costs_based_on_products_cost', 20, 2 );

function custom_shipping_costs_based_on_products_cost( $rates, $package ) {
    
    $products_amount = WC()->cart->cart_contents_total;
    $taxes_amount = WC()->cart->get_cart_contents_tax();
    $total = $products_amount + $taxes_amount;

    if ($total > 99.98) {
        foreach( $rates as $rate_key => $rate ){
            if( $rate->method_id == 'alg_wc_shipping:198'){
                $rates[$rate_key]->cost = 0;
            }
        }
    }

    return $rates;
}

不幸的是,代码不起作用,我找不到原因。我计算的部分

$total
工作正常,已经过测试。方法 ID 可在购物车 html 代码中找到:

<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_alg_wc_shipping198" value="alg_wc_shipping:198" class="shipping_method" checked="checked">

我也尝试删除条件并仅更改成本,也没有执行任何操作。

php wordpress woocommerce shipping-method
1个回答
0
投票

找到了!

$rate->method_id
应更改为
$rate->id
。这是完整的代码,针对多种方法进行了更新:

add_filter( 'woocommerce_package_rates', 'custom_shipping_costs_based_on_products_cost', 20, 2 );

function custom_shipping_costs_based_on_products_cost( $rates, $package ) {
    
    $products_amount = WC()->cart->cart_contents_total;
    $taxes_amount = WC()->cart->get_cart_contents_tax();
    $total = $products_amount + $taxes_amount;

    $free_methods = [
        'alg_wc_shipping:198',
        'alg_wc_shipping:222',
        'alg_wc_shipping:217',
        'alg_wc_shipping:219',
        'alg_wc_shipping:207',
        'alg_wc_shipping:212',
        'alg_wc_shipping:221',
    ];

    if ($total > 99.98) {
        foreach( $rates as $rate_key => $rate ){
            if (in_array($rate->id, $free_methods)) {
                $label = $rates[$rate_key]->label . ': бесплатно';
                $rates[$rate_key]->label = $label;
                $rates[$rate_key]->cost = 0;
                if ( has_taxes ) {
                    $rates[$rate_key]->taxes = false;
                }
            }
        }
    }

    return $rates;
}
© www.soinside.com 2019 - 2024. All rights reserved.