Hide specific shipping method depending on day time in WooCommerce

不想你离开。 提交于 2021-01-01 06:53:45

问题


I'm looking to create a PHP code snippet that I would add to my functions.php file but I'm not sure how to proceed.

Someone asked the same question 2 years ago (Woocommerce - disable certain shipping methods based on time of day) but finally opted for a plugin that does that. I already use add-ons for detailed delivery options and I don't want to change or add another one just for this simple function if something can be done easily with php.

So I'm looking to disable a shipping method if the client order after 11AM (website time zone).

So I have this code for now :

if (date('H') > 11) { 
     $shippingmethod1.disable();
}

Can someone give me the proper code to make it work?


回答1:


This is quiet simple using woocommerce_package_rates filter hook.

Now you need to find out what is the shipping rate Id reference that you need to target. For that you will inspect the desired shipping method radio button (<input> field) with your browser tools to get value as shown below:

Once you get it you will set that in the code below:

add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_time', 10, 2 );
function hide_shipping_method_based_on_time( $rates, $package )
{
    // Set your default time zone (http://php.net/manual/en/timezones.php)
    date_default_timezone_set('Europe/London');
    
    // Here set your shipping rate Id
    $shipping_rate_id = 'local_pickup:13';

    // When this shipping method is available and after 11 AM
    if ( array_key_exists( $shipping_rate_id, $rates ) && date('H') > 11 ) {
        unset($rates[$shipping_rate_id]); // remove it
    }
    return $rates;
}

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

Clearing shipping caches:

  • You will need to empty your cart, to clear cached shipping data
  • Or In shipping settings, you can disable / save any shipping method, then enable back / save.


来源:https://stackoverflow.com/questions/63946611/hide-specific-shipping-method-depending-on-day-time-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!