READ FIRST: This code needs to be added at the end of the functions.php file. If you are familiar with editing functions.php, feel free to continue reading. If you haven’t done this before, adding this code in the wrong place might bring the site down and the only way to access it is by editing functions.php file again via FTP. Feel free to contact us if you need help!
If you want to show a custom message at the checkout for users who have unused coupons they received from referring people, add this code to functions.php file:
add_action('woocommerce_before_checkout_form', 'show_referral_coupons_message');
function show_referral_coupons_message() {
$userId = get_current_user_id();
if($userId === 0) {
return;
}
$user_info = get_userdata(get_current_user_id());
$user_email = $user_info->user_email;
$args = array(
'posts_per_page' => 99,
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'customer_email',
'value' => $user_email,
'compare' => 'LIKE'
)
)
);
$coupons = get_posts( $args );
if(empty($coupons)) {
return;
}
$availableCoupons = [];
foreach($coupons as $coupon) {
$couponUsage = get_post_meta($coupon->ID,'usage_count', true);
$usageLimit = get_post_meta($coupon->ID,'usage_limit', true);
if($couponUsage < $usageLimit || $usageLimit === '') {
array_push($availableCoupons, $coupon);
}
}
if(!empty($availableCoupons)) {
wc_print_notice( __('You have unused referral coupons. Add them to get a discount.'), 'notice' );
}
}