我试图显示购物车中最高的运费。我为此找到了一个不错的小片段:
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);
但是,此代码段也隐藏了“本地取货”运输方式。
为什么上面的方法不起作用?现在它只显示最高的运输等级/价格,并隐藏所有其他的,包括提货方式。
是因为两个数组吗?我没有看到任何错误弹出。
非常感谢任何帮助!