Search code examples
phpwordpresswoocommercehook-woocommerceshipping-method

Shipping methods based on a defined date threshold in WooCommerce


I want to enable the two shipping methods in WooCommerce like If the user order before the particular date then I want to enable the 1st shipping method and when the user order after the particular date then I want to enable the 2nd shipping method. Can anyone let me know if there is any plugin or code to do this functionality?


Solution

  • The following code will enable a different shipping methods based on a defined date threshold.

    You will have to defined in the function, your settings for:
    - The shop timezone
    - The 2 shipping methods rate IDs (like 'flat_rate:12' format)
    - The date threshold

    The code:

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

    Code goes on function.php file of your active child theme (or active theme). Tested and works.

    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..

    To get the correct shipping methods rate id, inspect their radio buttons code with your browsers tools (in cart or checkout pages), and use the value attribute data like:

    <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"