简体   繁体   中英

How to use customer email address as their own coupon code in woocommerce

I am trying to use customer email address as their own coupon code with a special discount. To achieve this I tried bellow code but nothing happen shows error Call to undefined function get_currentuserinfo() . Is it possible to use coupon code virtually not saving like custom post_type ?

Here is the code what I'm trying so far.

global $current_user;

get_currentuserinfo();
$user_email = $current_user->user_email ;

$coupon_code = $user_email; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

// 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', 'no' );
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', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

The get_currentuserinfo() function is deprecated. Use wp_get_current_user() instead.

You should use in your code:

// (Optional) depending where you are using this code
is_user_logged_in(){

    global $current_user;

    // If global $current_user is not working
    if(empty($current_user))
        $current_user = wp_get_current_user();

    // Here goes all your other code below… …

}

After that, I have never tried to set an email as coupon code slug programatically, but it should work as it's possible to set in woocommerce a coupon code with an email address (I have test it with success)…

    add_action( 'user_register', 'coupon_email', 10, 1 );

    function coupon_email( $user_id ) {

        if ( isset( $_POST['email_address'] ) )
            $coupon = array(
        'post_title' => $_POST['email_address'],
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type'     => 'shop_coupon'
    );

    $new_coupon_id = wp_insert_post( $coupon );

}

This will add a coupon with the users email address as the title and input every time a new user registers for your website.

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