I have generated coupon code dynamically for each customer when they purchasing a product from the website and i have set certain conditions.
When I have dynamically created a coupon code, it stored in woocommerce > coupons section.
function couponCodeGeneration($order_id, $i){
// Get the order ID
$coupon_code = $order_id."".$i; // Coupon Code
$amount = '100%'; // Amount
$discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product
wp_coupon_exist( $coupon_code );
if( wp_coupon_exist( $coupon_code ) ) {
//coupon code exists.
} else {
//coupon code not exists, so inserting coupon code
$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
//'post_category' => array(1)
);
$new_coupon_id = wp_insert_post( $coupon );
//SET THE PRODUCT CATEGORIES
wp_set_object_terms($post_id, 'Holiday Season offers', 'product_cat');
// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'expiry_date', '2019-07-31' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
update_post_meta( $new_coupon_id, 'limit_usage_to_x_items', '1' );
update_post_meta( $new_coupon_id, 'usage_limit_per_user', '1' );
update_post_meta( $post_id, 'times', '1' );
echo '<div class="couponCode"><strong>Your Coupon Code for your next purchase - '.$coupon_code.'</strong><hr></div>';
}
}
I need help in the following situation.
The generated coupon code should not be used by another customer. The coupon only personal to that customer. Coupon code cannot be transferred.
When customer placing an order, the generated coupon code not stored in admin orders page. How do I know which coupon code is generated by which customer.
Can someone give me a suggestions.
I have fixed my issue.
Add the following code in functions.php
add_filter( 'woocommerce_coupon_is_valid', 'wc_riotxoa_coupon_is_valid', 20, 2 );
if ( ! function_exists( 'wc_riotxoa_coupon_is_valid' ) ) {
function wc_riotxoa_coupon_is_valid( $result, $coupon ) {
$user = wp_get_current_user();
$restricted_emails = $coupon->get_email_restrictions();
return ( in_array( $user->user_email, $restricted_emails ) ? $result : false );
}
}
Ref: https://gist.github.com/riotxoa/f4f1a895052c195394ba4841085a0e83