-1

I created an order in WooCommerce programmatically using wc_create_order(), and I also would like to apply coupon in some cases. I did it on my own way, but I'm not sure it's correct:

// Products come in $_GET
foreach($_GET['product'] as $p) {
    if(!isset($p['name'])) {
        continue;
    }

    if(!empty($p['name'])) {
        // Discount
        $discount = (int)$p['discount']/100;

        $product->set_name($p['name']);

        // I set the discount price
        $product->set_price(str_replace(' ', '', $p['price'])*(1-$discount));
        $discount_total += str_replace(' ', '', $p['price'])*$discount;
        $order->add_product( $product, $p['qty']);
    }
}

// I apply the coupon code
if(!empty($discount)) {
    $order->add_coupon('vip', $discount_total);
}

It's almost perfect, but I don't see the discount amount under summary and items table.

Is there an other way to apply the coupon?

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
user1452062
  • 805
  • 4
  • 12
  • 27

1 Answers1

-1

Here you can add the coupon by this way please change the content according to your need
add_action( 'woocommerce_before_cart', 'apply_coupons' );

function apply_coupons() {

    $coupon_code = 'freeweek'; 

    if ( WC()->cart->has_discount( $coupon_code ) ) return;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

    // this is your product ID
    $autocoupon = array( 745 );

    if( in_array( $cart_item['product_id'], $autocoupon ) ) {   
        WC()->cart->add_discount( $coupon_code );
        wc_print_notices();
    }

    }

}
Problem Solver
  • 422
  • 2
  • 9