我试图根据其他运输方式的可用性(通过其 ID)隐藏运输方式,以实现稍微复杂的运输设置。
根据我发现的其他代码片段(对于其他用例,排除州或仅显示免费送货(如果有)),我想出了这个:
function hide_duplicate_shipping_methods ( $rates ) {
foreach ( $rates as $rate_id => $rate ) {
if ( 'flat_rate:10' === $rate->method_id ) {
unset( $rates['flat_rate:28'] );
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_duplicate_shipping_methods', 100 );
但是,这并没有隐藏任何东西,我真的找不到或想到任何其他东西。
有什么建议吗?
$rate->method_id
将等于 local_pickup
、free_shipping
、flat_rate
等..
而
$rate_id
将等于local_pickup:1
、free_shipping:2
等..
所以你要么像这样使用它:
function filter_woocommerce_package_rates( $rates, $package ) {
// Loop trough
foreach ( $rates as $rate_id => $rate ) {
// Checks if a value exists in an array, multiple can be added, separated by a comma
if ( in_array( $rate->method_id, array( 'local_pickup', 'free_shipping' ) ) ) {
unset( $rates['flat_rate:28'] );
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
或者像这样:
function filter_woocommerce_package_rates( $rates, $package ) {
// Loop trough
foreach ( $rates as $rate_id => $rate ) {
// Checks if a value exists in an array, multiple can be added, separated by a comma
if ( in_array( $rate_id, array( 'local_pickup:1', 'free_shipping:2' ) ) ) {
unset( $rates['flat_rate:28'] );
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
代码位于活动子主题(或活动主题)的
functions.php
文件中。已在 Wordpress 5.8.1 和 WooCommerce 5.8.0 中测试并运行
不要忘记清空购物车以刷新运输缓存数据。
function amitg_woo_shipping_when_free_is_available( $rates ) {
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->get_method_id() ) {
$free[ $rate_id ] = $rate;
}
}
return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'amitg_woo_shipping_when_free_is_available', 100 );