以编程方式添加虚拟优惠券而不干扰常规优惠券的正确方法:
add_action(\'woocommerce_before_calculate_totals\', function(WC_Cart $cart) {
$cart->applied_coupons = array_diff($cart->applied_coupons, [\'store-credit\']);
// add your conditions for applying the virtual coupon
$cart->applied_coupons[] = \'store-credit\';
});
// specify discount data, here give 10% discount
add_filter(\'woocommerce_get_shop_coupon_data\', function($false, $data, $coupon) {
switch($data) {
case \'store-credit\':
$coupon->set_virtual(true);
$coupon->set_discount_type(\'percent\');
$coupon->set_amount(10);
return $coupon;
}
}, 10, 3);
// Optional: remove the \'Coupon:\' label
add_filter(\'woocommerce_cart_totals_coupon_html\', function($coupon_html, $coupon, $discount_amount_html) {
if (in_array($coupon->get_code(), [\'store-credit\']))
return $discount_amount_html;
return $coupon_html;
}, 10, 3);
// Optional: set a custom label
add_filter(\'woocommerce_cart_totals_coupon_label\', function($label, $coupon) {
switch ($coupon->get_code()) {
case \'store-credit\':
return \'Store Credit\';
}
return $label;
}, 10, 3);