简体   繁体   中英

Woocommerce coupon code for personalized customer

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.

Since Woocommerce 3 your code is really outdated, with a lot of mistakes. wp_coupon_exist() function doesn't exist.

To restrict the coupon to a specific customer, you can use Email restrictions WC_Coupon method that will also allow you to know which customer has generated the coupon code.

You could also set a some custom meta data if needed saving the user ID or the user complete name.

So there is two functions in my code:

  • The first one that checks if the coupon code doesn't exist
  • The second one that generate the coupon code as you planned.

The code:

// Utility function that check if coupon exist
function does_coupon_exist( $coupon_code ) {
    global $wpdb;

    $value = $wpdb->get_var( "
        SELECT ID
        FROM {$wpdb->prefix}posts
        WHERE post_type = 'shop_coupon'
        AND post_name = '".strtolower($coupon_code)."'
        AND post_status = 'publish';
    ");

    return $value > 0 ? true : false;
}


function coupon_code_generation( $order_id, $i ){
    $coupon_code = $order_id."".$i; // Coupon Code

    // Check that coupon code not exists
    if( ! does_coupon_exist( $coupon_code ) ) {

        // Get a new instance of the WC_Coupon object
        $coupon = new WC_Coupon();

        // Get the instance of the WC_Order object
        $order = wc_get_order( $order_id );

        ## --- Coupon settings --- ##

        $discount_type  = 'percent'; // Type
        $coupon_amount  = '100'; // Amount
        $customer_email = array( $order->get_billing_email() ); // Customer billing email
        $product_categories_names = array('Holiday Season offers');
        $date_expires = '2019-07-31';

        // Convert to term IDs
        $term_ids = array();
        foreach( $product_categories_names as $term_name ) {
            if ( term_exists( $term_name, 'product_cat' ) )
                $term_ids[] = get_term_by( 'name', $term_name, 'product_cat' )->term_id;
        }


        ## --- Coupon settings --- ##

        // Set the necessary coupon data
        $coupon->set_code( $coupon_code );
        $coupon->set_discount_type( 'percent' );
        $coupon->set_amount( 100 );
        if( is_array($term_ids) && sizeof($term_ids) > 0 )
            $coupon->set_product_categories( $term_ids );
        $coupon->set_email_restrictions( $customer_email );
        $coupon->set_individual_use( true );
        $coupon->set_usage_limit( 1 );
        $coupon->set_usage_limit_per_user( 1 );
        $coupon->set_limit_usage_to_x_items( 1 );
        $coupon->set_date_expires( date( "Y-m-d H:i:s", strtotime($date_expires) ) );

        // Save the data
        $post_id = $coupon->save();
    }
    echo isset($post_id) && $post_id > 0 ? sprintf(
        '<div class="couponCode"><strong>%s <code>%s</code></strong>.<hr></div>',
        __("Your Coupon Code for your next purchase is", "woocommerce"), $coupon_code
    ) : __("Sorry, a coupon code already exist.", "woocommerce");
}

Code goes in function.php file of your active child theme (or active theme). tested and works.

You will get an output something like (when the coupon is generated):

Your Coupon Code for your next purchase is 1198A

Or if coupon exist:

Sorry, a coupon code already exist.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM