Php Woocommerce-添加优惠券不扣除总额

Php Woocommerce-添加优惠券不扣除总额,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我正在创建我的订单,如下所示: $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-&g

我正在创建我的订单,如下所示:

$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();
如果您仔细看一下,我将添加一个优惠券代码dynamicali,其中包含WC_Order类中的add_优惠券函数。一切都很完美,订单以正确的产品、数量添加到数据库中,优惠券也被添加到数据库中——但问题是优惠券没有“应用”到总数中。它不是扣除总价。图为:

向订单添加产品时,我们应该传递一个包含小计和总计的参数,如下所示:

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

其中,
$product
是Woocommerce产品。希望这对其他人有所帮助。

以下是在我的案例中有效的解决方案,用于修改订单行项目,然后在之后应用折扣-$order是WC_订单对象:

    $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_订单对象的优惠券代码的方法。就我而言,我知道每个订单的优惠券数量永远不会超过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;
    }
}

你解决过这个问题吗?我遇到了同样的问题。我也遇到了同样的问题:(我尝试了很多方法,但没有找到解决方案。有人得到了答案吗?我在向订单添加产品时传递了一个参数,解决了这个问题:$args=array(“totals”=>array('subtotal'=>$price,'total'=>price-$coups\u折扣))$order->add_product($product,1,$args);@ShwethaU我认为你应该发布你的答案,因为它会帮助其他人。:D无论如何,谢谢你提供的信息。当然;)我会将它作为答案发布。。