基于 WooCommerce 中定义的日期阈值的运输方法

Shipping methods based on a defined date threshold in WooCommerce

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

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

您必须在函数中定义,您的设置为:
- 商店时区
- 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 文件中继续。已测试并有效。

To make it work, you should need to refresh the shipping cached data:
1) First, paste and save this code on your function.php file.
2) In the Shipping settings, enter to a Shipping Zone, then disable a Shipping Method and "save" and re-enable it and "save". You are done..

要获得正确的送货方式费率 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">

… so here it is flat_rate:12 in value="flat_rate:12"