以编程方式将优惠券应用于WooCommerce订单

时间:2018-11-01 09:40:35

标签: wordpress woocommerce

我使用wc_create_order()以编程方式在WooCommerce中创建了一个订单,在某些情况下,我还想申请优惠券。我是用自己的方式做到的,但我不确定它是正确的:

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

这几乎是完美的,但是我在摘要和项目表下看不到折扣金额。

还有其他方法可以应用优惠券吗?

enter image description here

1 个答案:

答案 0 :(得分:-1)

在这里您可以通过这种方式添加优惠券,请根据需要更改内容
    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();
    }

    }

}
相关问题