1

在 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 );

现在我们想保持快递运输以及本地取货。但是,应预先选择免费送货。

有谁知道我们如何自定义代码?

我们的运输方式费率 ID 为:

  • 正常交货(Versandkosten): legacy_flat_rate
  • 快递(Expressversand)legacy_flat_rateexpress
  • 免费送货(kostenloser Versand) :legacy_free_shipping
  • 本地取件(Abholung vor Ort)legacy_local_pickup
4

1 回答 1

1

要仅隐藏正常交付,当“免费送货”可用时,您将需要一些不同的东西:

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;
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。测试和工作。

刷新运输缓存:( 必需)

  1. 此代码已保存在活动主题的 function.php 文件中。
  2. 购物车是空的
  3. 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
于 2019-04-28T19:06:50.323 回答