Wordpress 如何在WooCommerce中动态更改优惠券金额并将其显示在购物车总计中

Wordpress 如何在WooCommerce中动态更改优惠券金额并将其显示在购物车总计中,wordpress,woocommerce,Wordpress,Woocommerce,我已经创建了一张Woocommerce优惠券,其折扣类型设置为固定购物车折扣和初始优惠券金额 我希望优惠券能够在客户输入优惠券代码时计算总折扣,并将其设置为优惠券金额。我正在主题的function.php中使用woocommerce\u applicated\u优惠券挂钩 我是这样编码的: add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 3 ); function action

我已经创建了一张Woocommerce优惠券,其折扣类型设置为固定购物车折扣和初始优惠券金额

我希望优惠券能够在客户输入优惠券代码时计算总折扣,并将其设置为优惠券金额。我正在主题的function.php中使用woocommerce\u applicated\u优惠券挂钩

我是这样编码的:

add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon', 10, 3 );

function action_woocommerce_applied_coupon( $array, $int, $int ){
  $total_discount = 0;
  $wc = wc();//use the WC class

  foreach($wc->cart->get_cart() as $cart_item){
    //loop through each cart line item

    $total_discount += ...; //this is where the total discount is computed
  }

  //use the WC_COUPON class
  $wc_coupon = new WC_Coupon("coupon-code");// create an instance of the class using the coupon code
  $wc_coupon->set_amount($total_discount);//set coupon amount to the computed discounted price
  var_dump($wc_coupon->get_amount());//check if the coupon amount did update
}
var_转储显示$total_折扣。但是,当我检查购物车总数时,我仍然将初始优惠券金额视为折扣

如何更新优惠券金额并将其作为折扣应用于购物车总额?

试试这个

add_action( 'woocommerce_before_calculate_totals', 'auto_add_coupons_total_based', 10, 1 ); function auto_add_coupons_total_based( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

// HERE define your coupon code
$coupon_percent = 'xyz20'; # <===  <===  <===  <===  <===  <===
$coupon_fixed = 'fixedamount'; # <===  <===  <===  <===  <===  <===  <===

// Get cart subtotal
$subtotal = 0;
foreach($cart->get_cart() as $cart_item ){
    $subtotal += $cart_item['line_subtotal'];
    $subtotal += $cart_item['line_subtotal_tax']; // with taxes
}

//Set HERE the limit amount
$limit = 40; //without Tax


// Coupon type "percent" (less than 200)
if( $subtotal < 200 && ! $cart->has_discount( $coupon_percent ) ){
    // If coupon "fixed amount" type is in cart we remove it
    if( $cart->has_discount( $coupon_fixed ) )
        $cart->remove_coupon( $coupon_fixed );


}
// Coupon type "fixed amount" (Up to 200)
if( $subtotal >= 200 && $cart->has_discount( $coupon_percent ) ) {
    // If coupon "percent" type is in cart we remove it
    if( $cart->has_discount( $coupon_percent ) )
        $cart->remove_coupon( $coupon_percent );

    // Apply the "fixed amount" type coupon code
    $cart->add_discount( $coupon_fixed );


    // Displaying a custom message
        $message = __( "The total discount limit of $$limit has been reached", "woocommerce" );
        wc_add_notice( $message, 'notice' );



}
add_动作('woocommerce_-before_-calculate_-total','auto_-add_-coups_-total_-based',10,1);功能自动添加优惠券总额($cart){
if(定义了('DOING'uajax'))
返回;
//这里定义您的优惠券代码

$coupon_percent='xyz20'#我认为您需要更新与优惠券相关的购物车行,var_dump cart或查看WC_cart类,希望这对您有所帮助。