【问题标题】:How to programmatically remove applied discount coupons in Woocommerce?如何以编程方式删除 Woocommerce 中应用的折扣券?
【发布时间】:2014-12-22 00:39:51
【问题描述】:

我已经搜索了一段时间,但找不到如何以编程方式删除 woocommerce 优惠券。

我正在尝试根据购物车总数进行折扣。我需要申请删除优惠券,因为如果您有价值 1000 欧元的产品(应用了 15% 的优惠券)并删除了产品并只留下价值 50 欧元的产品,您仍然可以获得 15% 的折扣,因为我的代码没有删除已经应用的优惠券.

这是我现在的代码:

    add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

$coupon_code5 = '5p'; // your coupon code here
$coupon_code10 = '10p'; // your coupon code here
$coupon_code15 = '15p'; // your coupon code here
$coupon_code20 = '20p'; // your coupon code here
$coupon_code25 = '25p'; // your coupon code here

   if ( $woocommerce->cart->has_discount( $coupon_code ) ){ 
return;
}

   if ( $woocommerce->cart->cart_contents_total >= 4000 ) {
        $woocommerce->cart->add_discount( $coupon_code25 );
        $woocommerce->show_messages();
    }
else if ( $woocommerce->cart->cart_contents_total >= 2000 ) {
        $woocommerce->cart->add_discount( $coupon_code20 );
        $woocommerce->show_messages();
    }
else if ( $woocommerce->cart->cart_contents_total >= 1000 ) {
        $woocommerce->cart->add_discount( $coupon_code15 );
        $woocommerce->show_messages();
    }
else if ( $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code10 );
        $woocommerce->show_messages();
    }
else if ( $woocommerce->cart->cart_contents_total >= 200 ) {
        $woocommerce->cart->add_discount( $coupon_code5 );
        $woocommerce->show_messages();
    }
}

【问题讨论】:

    标签: wordpress woocommerce discount coupon


    【解决方案1】:

    要使用优惠券代码从购物车中删除一张优惠券,请使用WC_Cart->remove_coupon( $code )

    要从购物车中删除所有优惠券,您将使用WC_Cart->remove_coupons( $type ) - $type 默认为null,传入“购物车”以删除税前优惠券,“订购”以删除税后优惠券。

    要以array 的形式获取购物车中的所有优惠券,您可以循环并选择删除,请使用WC_Cart->get_coupons()

    foreach ( WC()->cart->get_coupons() as $code => $coupon ){
       $valid = ? // decide to remove or not
       if ( ! $valid ){
           WC()->cart->remove_coupon( $code );
       }
    }
    

    【讨论】:

    • 删除优惠券对我有用,但折扣总额仍然存在。如何通过 Ajax 更新购物车总数?
    • @nickstaw 将 WC()->cart->calculate_totals(); 放在 WC()->cart->remove_coupon( $code ); 之后,这将重新计算购物车的总数
    【解决方案2】:

    购物车方法 remove_coupons() 已更新,不再需要类型。现在,要删除所有优惠券,这样就可以了:

    WC()->cart->remove_coupons();

    有关更多信息,请查看 WC_Cart 类 here 的文档。

    【讨论】:

    • 谢谢!不知道这个:)
    • 我在使用此方法时发现,虽然它确实删除了所有应用于购物车的现有优惠券,但它并没有重新计算价格。
    猜你喜欢
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    相关资源
    最近更新 更多