Generate one-use coupon for first-time customers

0.0/5
<?php
add_action( 'woocommerce_checkout_order_created', 'generate_custom_coupon' );
function generate_custom_coupon( $order ) {

	global $wpdb;
	$table = $wpdb->prefix . 'postmeta';
	$query   = $wpdb->prepare( "SELECT meta_id FROM $table WHERE meta_key = '_billing_email' AND meta_value = '%s'", array( $order->get_billing_email() ) );
	$results = $wpdb->get_results( $query );
	if ( !empty( $results ) && count( $results ) == 1 ) {

	   	$code = '';
        $keys = array_merge( range( 0, 9 ), range( 'a', 'z' ) );

        for ($i = 0; $i < 10; $i++) {
            $code .= $keys[array_rand( $keys )];
        }

		$code = strtoupper( $code );

		$coupon_args = array(
			'post_title' 	=> $code,
			'post_content' 	=> '',
			'post_status' 	=> 'publish',
			'post_author' 	=> 1,
			'post_type' 	=> 'shop_coupon'
		);
		   
		$coupon_id = wp_insert_post( $coupon_args );

		update_post_meta( $coupon_id, 'discount_type', 'percent' );
		update_post_meta( $coupon_id, 'coupon_amount', 10 );
		update_post_meta( $coupon_id, 'free_shipping', 'no' );
		update_post_meta( $coupon_id, 'usage_limit', 1 );
    
		update_post_meta( $order->get_id(), 'generated_coupon', $code );
		update_post_meta( $order->get_id(), 'generated_coupon_id', $coupon_id );
    
	}

}

Comments and reviews

{{ reviewsTotal }} Review
{{ reviewsTotal }} Reviews
{{ options.labels.newReviewButton }}
{{ userData.canReview.message }}

Description

This snippet generates one-use coupon for first-time customers

Author

Tags