【问题标题】:Woocommerce - Add Coupon is not deducting totalsWoocommerce - 添加优惠券不扣除总数
【发布时间】:2015-08-27 09:34:55
【问题描述】:

我正在这样创建我的订单:

$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' => $price, 'total' = > $price - $coupon_discount) ); $order->add_product($product, 1, $args);
  • @ShwethaU 我相信你应该发布你的答案,因为它会帮助其他人。 :D 无论如何感谢您的信息。
  • 当然 ;) 我会把它作为答案发布..

标签: php wordpress woocommerce


【解决方案1】:

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

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

$product 是 Woocommerce 产品。希望这对某人有所帮助。

【讨论】:

    【解决方案2】:

    在我的情况下,这是修改订单行项目然后应用折扣的解决方案 - $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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      相关资源
      最近更新 更多