【问题标题】:Disable free shipping for specific coupon type in WooCommerce在 WooCommerce 中禁用特定优惠券类型的免费送货
【发布时间】:2021-10-28 23:20:24
【问题描述】:

我正在使用Disable free shipping for specific coupon codes in WooCommerce 答案代码

我想定位优惠券类型而不是特定代码。我该怎么办?我想将 'smart_coupons' 定位为类型。

更新 - 这是我想出的,虽然加载需要相当长的时间。它可能只是我的 WP,因为我有很多优惠券。有什么方法可以在结帐时只调用输入的优惠券而不是所有优惠券?

add_filter( 'woocommerce_package_rates', 'hide_free_shipping_method_based_on_coupons', 10, 2 );
function hide_free_shipping_method_based_on_coupons( $rates, $package )
{
    $coupons            = WC()->cart->get_coupons();
    $applied_coupons    = WC()->cart->get_applied_coupons(); // Applied coupons
    
    foreach($coupons as $coupon_code) {
    $coupon = new WC_Coupon( $coupon_code );
    echo $coupon->get_discount_type();
    }
    
    if($coupon->get_discount_type() === 'smart_coupon') {
    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;
}

【问题讨论】:

  • 你能指定优惠券类型或折扣类型吗?
  • 请注意这不是代码编写或辅导服务。我们可以帮助解决具体的技术问题,而不是对代码或建议的开放式请求。请编辑您的问题以显示what you have tried so far to solve your problem,以及您需要帮助的具体问题。请参阅How to Ask 页面,详细了解如何最好地帮助我们。
  • 折扣类型是'smart_coupons'

标签: php wordpress woocommerce coupon shipping-method


【解决方案1】:

问题不清楚您想要实现什么。 阅读更多关于 WC_Coupon 的信息here

这里有一些提示:

function check_coupon_type() {
    //Following function will show coupon discount type on checkout page
        // We need to get all coupons used.
        $coupons = WC()->cart->get_coupons();
        // Loop each of them and echo discount type.
        foreach($coupons as $coupon_code) {
            $coupon = new WC_Coupon( $coupon_code );
            echo $coupon->get_discount_type();
        }
}
//Depending on what you want to check / restrict hook to the proper action
add_action( 'woocommerce_before_checkout_form', 'check_coupon_type', 10, 0 );

【讨论】:

  • 我想定位优惠券类型而不是特定代码数组
  • 以上示例返回折扣类型(百分比、固定购物车或固定产品)。这些是 woocommerce 的默认优惠券类型。在 foreach 循环中,您可以 var_dump($coupon) 查看所有数据。从那里你可以根据你的需要做一些条件,例如 - if($coupon->get_discount_type() === 'percent') { do stuff }