【问题标题】:Keep highest flat rate shipping cost and local pickup in Woocommerce在 Woocommerce 中保持最高的统一运费和本地取货
【发布时间】:2019-01-02 15:16:49
【问题描述】:

我试图在购物车中显示最高的运费。我为此找到了一个不错的小 sn-p:

function only_show_most_expensive_shipping_rate( $rates, $package ) {
    $most_expensive_method = '';
    $new_rates = array();
    // Loop through shipping rates
    if ( is_array( $rates ) ) {
        foreach ( $rates as $key => $rate ) {   
         // Set variables when the rate is more expensive than the one saved
         if ( empty( $most_expensive_method ) || $rate->cost > $most_expensive_method->cost ){
            $most_expensive_method = $rate;
         }

        }
    }
    // Return the most expensive rate when possible
    if ( ! empty( $most_expensive_method ) ){
       /**  
        ** Keep local pickup if it's present.
        **/
        foreach ( $rates as $rate_id => $rate ) {
            if ('local_pickup' === $rate->method_id ) {
                $new_rates[ $rate_id ] = $rate;
                break;
            }
        }
        return array( $most_expensive_method->id => $most_expensive_method );
    }
    return $rates;
}
add_action('woocommerce_package_rates', 'only_show_most_expensive_shipping_rate', 10, 2); 

不过,这个 sn-p 也隐藏了“本地取货”运输方式。

为什么上面的方法不起作用?现在它只显示最高的运输等级/价格,并隐藏所有其他的,包括提货方式。

是不是因为两个数组?我没有看到任何错误弹出。

非常感谢任何帮助!

【问题讨论】:

    标签: php wordpress woocommerce shipping-method


    【解决方案1】:

    以下将保持最高的统一运费和本地取货运输方式:

    add_action('woocommerce_package_rates', 'keep_highest_flat_rate_cost', 10, 2);
    function keep_highest_flat_rate_cost( $rates, $package ) {
        $flat_rate_costs = [];
    
        // Loop through shipping methods rates
        foreach ( $rates as $key_rate => $rate ) {
            // Targeting only "Flat rate" type shipping methods
            if ( ! in_array( $rate->method_id, ['local_pickup', 'free_shipping'] ) ) {
                // Store the Rate ID keys with corresponding costs in an indexed array
                $flat_rate_costs[$key_rate] = $rate->cost;
            }
        }
        // Sorting "Flat rate" costs in DESC order
        arsort($flat_rate_costs);
    
        // Remove the highest cost from the array
        array_shift($flat_rate_costs);
    
        // Loop through remaining "Flat rate" shipping methods to remove them all
        foreach ( $flat_rate_costs as $key_rate => $cost){
            unset($rates[$key_rate]);
        }
        return $rates;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    您应该需要刷新运输缓存:
    1) 首先确保代码已经保存在你的 function.php 文件中。
    2) 在配送设置中,输入配送区域:禁用任何配送方式并“保存”,然后重新启用并“保存”。 你已经完成了。

    【讨论】:

    • 效果很好!谢谢你。由于我正在学习 PHP,因此也感谢您的 cmets 关于做什么。从来没有想过排序,虽然这可能是我更了解的 javascript 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2021-04-11
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2015-01-03
    • 2019-02-20
    相关资源
    最近更新 更多