Based on "Fix maximum coupon Discount On Cart percentage in WooCommerce" answer thread, I use the following code in my active theme's function.php
file:
add_action('woocommerce_coupon_options_usage_limit', 'woocommerce_coupon_options_usage_limit', 10, 2);
function woocommerce_coupon_options_usage_limit($coupon_id, $coupon) {
echo '<div class="options_group">';
// max discount per coupons
$max_discount = get_post_meta($coupon_id, '_max_discount', true);
woocommerce_wp_text_input(array(
'id' => 'max_discount',
'label' => __('Usage max discount', 'woocommerce'),
'placeholder' => esc_attr__('Unlimited discount', 'woocommerce'),
'description' => __('The maximum discount this coupon can give.', 'woocommerce'),
'type' => 'number',
'desc_tip' => true,
'class' => 'short',
'custom_attributes' => array(
'step' => 1,
'min' => 0,
),
'value' => $max_discount ? $max_discount : '',
));
echo '</div>';
}
add_action('woocommerce_coupon_options_save', 'woocommerce_coupon_options_save', 10, 2);
function woocommerce_coupon_options_save($coupon_id, $coupon){
update_post_meta($coupon_id, '_max_discount', wc_format_decimal($_POST['max_discount']));
}
add_filter('woocommerce_coupon_get_discount_amount', 'woocommerce_coupon_get_discount_amount', 20, 5);
function woocommerce_coupon_get_discount_amount($discount, $discounting_amount, $cart_item, $single, $coupon){
$max_discount = get_post_meta($coupon->get_id(), '_max_discount', true);
if (isset($max_discount) && is_numeric($max_discount) && ($max_discount > 0) && !is_null($cart_item) && WC()->cart->subtotal_ex_tax) {
if($discount > $max_discount) {
$discount = $max_discount;
}
}
return $discount;
}
But this code is only active for one product in the shopping cart and does not work for several products in the cart.
What changes should I need to do to make it work for all cart items instead?
Any track is welcome.