簡體   English   中英

Woocommerce-加息券不扣除總數

[英]Woocommerce - Add Coupon is not deducting totals

我正在這樣創建訂單:

$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();

如果您仔細看一下,我將使用WC_Order類的add_coupon函數動態添加優惠券代碼。 一切正常,將訂單添加到具有正確產品,數量的數據庫,並且還添加了優惠券-但問題是優惠券未“應用”到總數中。 它沒有扣除總價 這是圖片: 在此處輸入圖片說明

在向訂單添加產品時,我們應該傳遞一個包含小計和總計的參數,如下所示:

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

其中$product是Woocommerce產品。 希望這對某人有幫助。

這是在我的案例中有效的解決方案,用於修改訂單行項目,然后再應用折扣-$ 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 );

這是檢索WC_Order對象的優惠券代碼的方法。 就我而言,我知道每個訂單永遠不會有超過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