在 WooCommerce 中禁用特定优惠券代码的免费送货 [英] Disable free shipping for specific coupon codes in WooCommerce

查看:34
本文介绍了在 WooCommerce 中禁用特定优惠券代码的免费送货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有人使用特定的优惠券代码时,我试图删除 Woocommerce 中的免费送货选项.我发现 这个问题与我的问题非常相关.下面的答案似乎与我正在寻找的非常接近.我是 php 的新手,正在想办法为要排除的优惠券代码添加一个 ID.

I am trying to remove the free shipping option in Woocommerce when someone uses a specific coupon code. 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.

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.

推荐答案

改用 woocommerce_package_rates 过滤器钩子.在下面的代码中,您将设置将隐藏免费送货方式的相关优惠券代码:

Use instead woocommerce_package_rates filter hook. 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;
}

代码位于活动子主题(或活动主题)的 functions.php 文件中.经测试有效.

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

清除运输缓存:

  • 您需要清空购物车,以清除缓存的运输数据
  • 或者在运输设置中,您可以禁用/保存任何运输方式,然后启用返回/保存.

这篇关于在 WooCommerce 中禁用特定优惠券代码的免费送货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆