Let’s say you don’t want one user to use the same coupon code multiple times. There is a default option in WooCommerce coupon settings to achieve this. But today we will try and achieve this using code.
function careless_coupon_multiple_usage_validation_filter( $is_valid, $coupon, $discount ) {
//check if coupon was used by current user
if ( in_array( (string) get_current_user_id(), $coupon->get_used_by() ) ) {
$is_valid = false;
}
return $is_valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'careless_coupon_multiple_usage_validation_filter', 10, 3 );
Above code will be triggered when a coupon is being added. It will check if the inputted coupon is valid. Once it passes all default WooCommerce checks, it will enter our function. $coupon->get_used_by
returns IDs of all the users who has already used this coupon. So we are comparing this with current user id, using get_current_user_id
method. If it finds current user id in the $coupon->get_used_by
array, coupon validation will return false
. Otherwise it will return true
and coupon will be applied.
Code goes in the functions.php
file of your active theme.