首页 > 解决方案 > 隐藏折扣小计低于 75 时,特定应用的优惠券免运费

问题描述

我正在尝试创建一种非常特定类型的优惠券代码。

现在该网站已经提供免费送货服务,但如果订单低于 75 英镑,我希望那些禁用,仅当应用此代码时

使用stackoverflow上的其他问题,我设法创建了代码,但它被应用于每一对夫妇。

如何将此代码仅应用于“allthings30”优惠券。任何帮助都会被大大占用。

add_filter( 'woocommerce_package_rates', 'coupons_removes_free_shipping', 33, 38 );
function coupons_removes_free_shipping( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    $min_subtotal      = 75; // Minimal subtotal allowing free shipping
    $coupon_code    = 'allthings30'; // The required coupon code

    // Get needed cart subtotals
    $subtotal_excl_tax = WC()->cart->get_subtotal();
    $subtotal_incl_tax = $subtotal_excl_tax + WC()->cart->get_subtotal_tax();
    $discount_excl_tax = WC()->cart->get_discount_total();
    $discount_incl_tax = $discount_total + WC()->cart->get_discount_tax();

    // Calculating the discounted subtotal including taxes
    $discounted_subtotal_incl_taxes = $subtotal_incl_tax - $discount_incl_tax;

    $applied_coupons = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() );

    if( sizeof($applied_coupons) > 0 && $discounted_subtotal_incl_taxes < $min_subtotal ){
        foreach ( $rates as $rate_key => $rate ){
            // Targeting "Free shipping"
            if( 'free_shipping' === $rate->method_id  ){
                unset($rates[$rate_key]);
            }
        }
    }
    return $rates;
}

标签: phpwordpresswoocommercecouponshipping-method

解决方案


你非常接近......以下将完成这项工作:

add_filter( 'woocommerce_package_rates', 'coupons_removes_free_shipping', 33, 38 );
function coupons_removes_free_shipping( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    $min_subtotal   = 75; // Minimal subtotal allowing free shipping
    $coupon_code    = 'summer'; // The required coupon code

    // Get cart subtotals and applied coupons
    $cart              = WC()->cart;
    $subtotal_excl_tax = $cart->get_subtotal();
    $subtotal_incl_tax = $subtotal_excl_tax + $cart->get_subtotal_tax();
    $discount_excl_tax = $cart->get_discount_total();
    $discount_incl_tax = $discount_excl_tax + $cart->get_discount_tax();
    $applied_coupons   = $cart->get_applied_coupons(); // Get applied coupons array

    // Calculating the discounted subtotal including taxes
    $disc_subtotal_incl_tax = $subtotal_incl_tax - $discount_incl_tax;

    if( in_array( strtolower($coupon_code), $applied_coupons ) && $disc_subtotal_incl_tax < $min_subtotal ){
        foreach ( $rates as $rate_key => $rate ){
            // Targeting "Free shipping"
            if( 'free_shipping' === $rate->method_id  ){
                unset($rates[$rate_key]);
            }
        }
    }
    return $rates;
}

将该代码保存到主题的 functions.php 文件后,不要忘记在管理员运费设置中刷新运费,禁用并保存任何运输方式,然后重新启用并将其保存回来......</p>


推荐阅读