首页 文章

如何动态更改优惠券金额并将其显示在WooCommerce的购物车总数中

提问于
浏览
1

我创建了一个Woocommerce优惠券,折扣类型设置为固定购物车折扣和初始优惠券金额 .

我希望优惠券以这样的方式运作:当顾客输入优惠券代码时,计算总折扣并将其设置为优惠券金额 . 我在主题的function.php中使用了woocommerce_applied_coupon挂钩 .

这是我编码的方式:

add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 3 );

function action_woocommerce_applied_coupon( $array, $int, $int ){
  $total_discount = 0;
  $wc = wc();//use the WC class

  foreach($wc->cart->get_cart() as $cart_item){
    //loop through each cart line item

    $total_discount += ...; //this is where the total discount is computed
  }

  //use the WC_COUPON class
  $wc_coupon = new WC_Coupon("coupon-code");// create an instance of the class using the coupon code
  $wc_coupon->set_amount($total_discount);//set coupon amount to the computed discounted price
  var_dump($wc_coupon->get_amount());//check if the coupon amount did update
}

var_dump显示$ total_discount . 但是当我检查购物车总计时,我仍然将最初的优惠券金额视为折扣 .

如何更新优惠券金额并将其作为折扣应用于购物车总数?

1 回答

  • 1

    试试这个

    add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupons_total_based', 10, 1 ); function auto_add_coupons_total_based( $cart ) {
    
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    // HERE define your coupon code
    $coupon_percent = 'xyz20'; # <===  <===  <===  <===  <===  <===
    $coupon_fixed = 'fixedamount'; # <===  <===  <===  <===  <===  <===  <===
    
    // Get cart subtotal
    $subtotal = 0;
    foreach($cart->get_cart() as $cart_item ){
        $subtotal += $cart_item['line_subtotal'];
        $subtotal += $cart_item['line_subtotal_tax']; // with taxes
    }
    
    //Set HERE the limit amount
    $limit = 40; //without Tax
    
    
    // Coupon type "percent" (less than 200)
    if( $subtotal < 200 && ! $cart->has_discount( $coupon_percent ) ){
        // If coupon "fixed amount" type is in cart we remove it
        if( $cart->has_discount( $coupon_fixed ) )
            $cart->remove_coupon( $coupon_fixed );
    
    
    }
    // Coupon type "fixed amount" (Up to 200)
    if( $subtotal >= 200 && $cart->has_discount( $coupon_percent ) ) {
        // If coupon "percent" type is in cart we remove it
        if( $cart->has_discount( $coupon_percent ) )
            $cart->remove_coupon( $coupon_percent );
    
        // Apply the "fixed amount" type coupon code
        $cart->add_discount( $coupon_fixed );
    
    
        // Displaying a custom message
            $message = __( "The total discount limit of $$limit has been reached", "woocommerce" );
            wc_add_notice( $message, 'notice' );
    
    
    
    }
    

    }

相关问题