在Woocommerce中,我们使用以下代码隐藏除免费送货以外的所有运输方式:
function my_hide_shipping_when_free_is_available( $rates ) {
$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', 'my_hide_shipping_when_free_is_available', 100 );
现在我们想保持快递运输以及本地取件。但是,应预先选择免费送货。
有没有人知道我们如何自定义代码?
我们的运输方式费率编号为:
- 正常交货(韦尔桑德科斯滕(:
legacy_flat_rate
- 快递:
legacy_flat_rateexpress
- 免费送货(kostenloser Versand(:
legacy_free_shipping
- 本地接送(Abholung vor Ort(:
legacy_local_pickup
要隐藏 仅正常送货,当"免费送货"可用时,您将需要一些不同的东西:
add_filter( 'woocommerce_package_rates', 'show_hide_shipping_methods', 100 );
function show_hide_shipping_methods( $rates ) {
// When "Free shipping" is available
if( isset($rates['legacy_free_shipping']) && isset($rates['legacy_flat_rate']) ) {
// Hide normal flat rate
unset($rates['legacy_flat_rate']);
}
return $rates;
}
以下会将"免费送货"设置为默认选择的送货方式:
add_filter( 'woocommerce_shipping_chosen_method', 'set_default_chosen_shipping_method', 10, 3 );
function set_default_chosen_shipping_method( $default, $rates, $chosen_method ) {
if( isset($rates['legacy_free_shipping']) ) {
$default = 'legacy_free_shipping';
}
return $default;
}
代码进入活动子主题(或活动主题(的函数.php文件。经过测试并工作。
刷新发货缓存:(必需(
- 此代码已保存在活动主题的功能.php文件中。
- 购物车是空的
- 在配送区域设置中,禁用/保存任何配送方式,然后启用返回/保存。