Last active
January 2, 2024 12:39
-
-
Save goranefbl/79956373667b6cd2fa18794d5a8b1e83 to your computer and use it in GitHub Desktop.
WooCommerce - Allow coupons to be usable by existing customers only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Made by Goran from https://wpgens.com | |
add_action( 'woocommerce_before_apply_coupon', 'check_order_history_before_coupon' ); | |
function check_order_history_before_coupon( $coupon_code ) { | |
// Assuming 'firstorder' is your coupon code | |
if ( strtolower( $coupon_code ) !== 'firstorder' ) { | |
return; | |
} | |
$user = wp_get_current_user(); | |
$email = ''; | |
$has_orders = false; | |
if ( $user->ID ) { | |
// For logged-in users | |
$orders = wc_get_orders( array( | |
'customer_id' => $user->ID, | |
'status' => 'completed' | |
)); | |
$has_orders = count( $orders ) > 0; | |
} else { | |
// For guests, check if there's an email in the current session | |
$email = WC()->session->get('customer')['email'] ?? ''; | |
if ( $email ) { | |
$orders = wc_get_orders( array( | |
'billing_email' => $email, | |
'status' => 'completed' | |
)); | |
$has_orders = count( $orders ) > 0; | |
} | |
} | |
if ( !$has_orders ) { | |
wc_add_notice( 'This coupon is only for customers who have already made an order.', 'error' ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment