Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Last active January 2, 2024 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goranefbl/79956373667b6cd2fa18794d5a8b1e83 to your computer and use it in GitHub Desktop.
Save goranefbl/79956373667b6cd2fa18794d5a8b1e83 to your computer and use it in GitHub Desktop.
WooCommerce - Allow coupons to be usable by existing customers only
<?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