简体   繁体   English

在 WooCommerce 中禁用特定优惠券代码的免费送货

[英]Disable free shipping for specific coupon codes in WooCommerce

I am trying to remove the free shipping option in Woocommerce when someone uses a specific coupon code.当有人使用特定的优惠券代码时,我试图删除 Woocommerce 中的免费送货选项。 I found this question which is very relevant to my question.我发现这个问题与我的问题非常相关。 The answer bellow seems really close to what I am looking for.下面的答案似乎与我正在寻找的非常接近。 I am new to php and trying to figure out where I would add an id for the coupon code I want to exclude.我是 php 的新手,并试图弄清楚我会在哪里为我想要排除的优惠券代码添加一个 id。

add_filter( 'woocommerce_shipping_packages', function( $packages ) {
  $applied_coupons = WC()->session->get('applied_coupons', array());

  if (!empty($applied_coupons)) {
    $free_shipping_id = 'free_shipping:2';
    unset($packages[0]['rates'][ $free_shipping_id ]);
  }

  return $packages;
});

This is my first question on stack over flow but this site has helped me so much with so many issues.这是我关于堆栈溢出的第一个问题,但是这个网站在很多问题上帮了我很多。 Forgive me if I am asking too much.如果我要求太多,请原谅我。 Thanks in advance for any help/guidance.提前感谢您的任何帮助/指导。

Use instead woocommerce_package_rates filter hook.改用woocommerce_package_rates过滤器钩子。 In the code below you will set the related coupon codes that will hide the free shipping method:在下面的代码中,您将设置将隐藏免费送货方式的相关优惠券代码:

add_filter( 'woocommerce_package_rates', 'hide_free_shipping_method_based_on_coupons', 10, 2 );
function hide_free_shipping_method_based_on_coupons( $rates, $package )
{
    $coupon_codes       = array('summer'); // <== HERE set your coupon codes
    $applied_coupons    = WC()->cart->get_applied_coupons(); // Applied coupons
    
    if( empty($applied_coupons) )
        return $rates;

    // For specific applied coupon codes
    if( array_intersect($coupon_codes, $applied_coupons) ) {
        foreach ( $rates as $rate_key => $rate ) {
            // Targetting "Free shipping"
            if ( 'free_shipping' === $rate->method_id ) {
                unset($rates[$rate_key]); // hide free shipping method
            }
        }
    }
    return $rates;
}

Code goes in functions.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 functions.php 文件中。 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.或者在运输设置中,您可以禁用/保存任何运输方式,然后启用返回/保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM