简体   繁体   English

Woocommerce-加息券不扣除总数

[英]Woocommerce - Add Coupon is not deducting totals

I am creating my order like so: 我正在这样创建订单:

$order = wc_create_order();

$product = wc_get_product( $_POST["product"] );
$order->add_product( $product, 1 );

$kupon = new WC_Coupon( $_POST["coupon"] );
$amount = $kupon->get_discount_amount( $product->price );
$order->add_coupon( $_POST["coupon"], $amount, $amount );

$order->calculate_shipping();
$order->calculate_totals();

If you take a closer look, I am adding a coupon code dynamicaly with add_coupon function from WC_Order class. 如果您仔细看一下,我将使用WC_Order类的add_coupon函数动态添加优惠券代码。 Everythings works perfectly, the order is added to database with correct product, quantites, and ALSO the coupon is added - but the problem is that coupon is not "applied" to the total. 一切正常,将订单添加到具有正确产品,数量的数据库,并且还添加了优惠券-但问题是优惠券未“应用”到总数中。 It is not deducting the totals price . 它没有扣除总价 Here is the image: 这是图片: 在此处输入图片说明

While adding a product to an Order, we should pass an argument containing subtotal and total like this: 在向订单添加产品时,我们应该传递一个包含小计和总计的参数,如下所示:

$args = array(
    "totals" => array('subtotal' => $item["price"],
                      'total' => $item["price"] - $coupon_discount)
);                      
$order->add_product( $product, 1, $args);

Where $product is Woocommerce product. 其中$product是Woocommerce产品。 Hope this helps somebody. 希望这对某人有帮助。

Here is the solution that worked in my case for modifying order line items then applying a discount afterward - $order is a WC_Order object: 这是在我的案例中有效的解决方案,用于修改订单行项目,然后再应用折扣-$ order是WC_Order对象:

    $order_total        = $order->get_total()
    $coupon_code        = $this->get_coupon_code( $order );
    $coupon             = new WC_Coupon( $coupon_code );
    $coupon_type        = $coupon->discount_type;
    $coupon_amount      = $coupon->coupon_amount;
    $final_discount     = 0;

    // You must calculate the discount yourself! I have not found a convenient method outside the WC_Cart context to do this for you.
    $final_discount = $coupon_amount * ( $order_total / 100 );

    $order->add_coupon( $coupon_code, $final_discount, 0 );
    $order->set_total( $final_discount );

Here is the method to retrieve the coupon code for a WC_Order object. 这是检索WC_Order对象的优惠券代码的方法。 In my case I know there will never be more then 1 coupon per order so you may want to adjust it to accommodate more: 就我而言,我知道每个订单永远不会有超过1张优惠券,因此您可能需要对其进行调整以容纳更多:

public function get_coupon_code( $subscription ) {

    $coupon_used = '';
    if( $subscription->get_used_coupons() ) {

      $coupons_count = count( $subscription->get_used_coupons() );

      foreach( $subscription->get_used_coupons() as $coupon) {
        $coupon_used = $coupon;
        break;
      } 
    }

    if ( $coupon_used !== '' ) {
        return $coupon_used;
    } else {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM