Auto apply a percentage or fixed cart discount based on the total in WooCommerce

后端 未结 2 1775
梦毁少年i
梦毁少年i 2021-01-15 11:13

I\'m trying to set up a coupon on my client\'s WooCommerce site so that a percentage discount applies if the total cart is below a cap amount or a fixed amount is equal or g

2条回答
  •  独厮守ぢ
    2021-01-15 12:00

    Ok so I finally figure out how to use this code so that it only triggers when the coupon is added. I also added a script to notify the buyer that the coupon discount limit has been reached

    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' );
    
    
    
    }
    

    }

提交回复
热议问题