Coupon Codes for First Orders Only
Limits chosen coupon codes, such as a welcome discount, to customers who have never placed a paid order, checked by account and billing email.
Opens WPIDE on
Code
$wpide_welcome_coupons = array( 'welcome10', 'firstorder' ); // Coupon codes.
add_filter( 'woocommerce_coupon_is_valid', function ( $valid, $coupon ) use ( $wpide_welcome_coupons ) {
if ( ! in_array( wc_format_coupon_code( $coupon->get_code() ), array_map( 'wc_format_coupon_code', $wpide_welcome_coupons ), true ) ) {
return $valid;
}
$email = is_user_logged_in() ? wp_get_current_user()->user_email : ( WC()->customer ? WC()->customer->get_billing_email() : '' );
$query = array( 'status' => wc_get_is_paid_statuses(), 'limit' => 1, 'return' => 'ids' );
$found = array();
if ( is_user_logged_in() ) {
$found = wc_get_orders( $query + array( 'customer_id' => get_current_user_id() ) );
}
if ( ! $found && is_email( $email ) ) {
$found = wc_get_orders( $query + array( 'billing_email' => $email ) );
}
if ( $found ) {
throw new Exception( esc_html( 'This welcome coupon is only valid on your first order.' ), 100 );
}
return $valid;
}, 10, 2 );
Notes
Guests are checked by the billing email entered at checkout, so the code may be accepted in the cart and refused at checkout.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.