1

我想在 WooCommerce 中启用两种运输方式,例如如果用户在特定日期之前订购,那么我想启用第一种运输方式,当用户在特定日期之后订购时,我想启用第二种运输方式。谁能告诉我是否有任何插件或代码可以执行此功能?

4

1 回答 1

1

以下代码将根据定义的日期阈值启用不同的运输方式。

您必须在函数中定义您的设置:
- 商店时区
- 2 种运输方式费率 ID (如 'flat_rate:12' 格式)
- 日期阈值

编码:

add_filter( 'woocommerce_package_rates', 'free_shipping_disable_flat_rate', 100, 2 );
function free_shipping_disable_flat_rate( $rates, $package ) {

    ## ----- YOUR SETTINGS HERE BELOW  ----- ##

    date_default_timezone_set('Europe/London'); // <== Set the time zone (http://php.net/manual/en/timezones.php)

    $shippping_rates = ['flat_rate:12', 'flat_rate:14']; // <== Set your 2 shipping methods rate IDs
    $defined_date    = "2019-03-05";                     // <== Set your date threshold

    ## ------------------------------------- ##

    $now_timestamp  = strtotime("now"); // Current timestamp in seconds
    $date_timestamp = strtotime($defined_date); // Targeted timestamp threshold

    // 1. BEFORE the specified date (with 1st shipping method rate ID)
    if ( array_key_exists( $shippping_rates[0], $rates ) && $now_timestamp > $date_timestamp ) {
        unset($rates[$shippping_rates[0]]); // Remove first shipping method
    }
    // 2. AFTER the specified date included (with 2nd shipping method rate ID)
    elseif ( array_key_exists( $shippping_rates[1], $rates ) && $now_timestamp <= $date_timestamp ) {
        unset($rates[$shippping_rates[1]]); // Remove Second shipping method
    }

    return $rates;
}

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

要使其工作,您应该需要刷新运输缓存数据:
1) 首先,将此代码粘贴并保存到您的 function.php 文件中。
2) 在配送设置中,进入配送区域,然后禁用配送方式并“保存”并重新启用并“保存”。你完成了。.

要获得正确的运输方式费率 ID,请使用浏览器工具(在购物车或结帐页面中)检查其单选按钮代码,并使用以下value属性数据:

<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate12" 
value="flat_rate:12" class="shipping_method" checked="checked">

......所以它就flat_rate:12在这里value="flat_rate:12"

于 2019-02-27T06:12:58.667 回答