Woocommerce coupon code for personalized customer












-1















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.










share|improve this question

























  • You should always include in your question the related code of your customizations (or if it is from an existing StackOverFlow answer, you should give the link). How are you generating the coupon code? Where is your code?

    – LoicTheAztec
    Nov 21 '18 at 21:15
















-1















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.










share|improve this question

























  • You should always include in your question the related code of your customizations (or if it is from an existing StackOverFlow answer, you should give the link). How are you generating the coupon code? Where is your code?

    – LoicTheAztec
    Nov 21 '18 at 21:15














-1












-1








-1


1






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.










share|improve this question
















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.







php wordpress woocommerce checkout coupon






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 26 '18 at 9:48









LoicTheAztec

94.2k1367107




94.2k1367107










asked Nov 21 '18 at 17:32









RathnaRathna

24




24













  • You should always include in your question the related code of your customizations (or if it is from an existing StackOverFlow answer, you should give the link). How are you generating the coupon code? Where is your code?

    – LoicTheAztec
    Nov 21 '18 at 21:15



















  • You should always include in your question the related code of your customizations (or if it is from an existing StackOverFlow answer, you should give the link). How are you generating the coupon code? Where is your code?

    – LoicTheAztec
    Nov 21 '18 at 21:15

















You should always include in your question the related code of your customizations (or if it is from an existing StackOverFlow answer, you should give the link). How are you generating the coupon code? Where is your code?

– LoicTheAztec
Nov 21 '18 at 21:15





You should always include in your question the related code of your customizations (or if it is from an existing StackOverFlow answer, you should give the link). How are you generating the coupon code? Where is your code?

– LoicTheAztec
Nov 21 '18 at 21:15












2 Answers
2






active

oldest

votes


















1














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.







share|improve this answer































    -1














    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






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417670%2fwoocommerce-coupon-code-for-personalized-customer%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      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.







      share|improve this answer




























        1














        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.







        share|improve this answer


























          1












          1








          1







          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.







          share|improve this answer













          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.








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 1:26









          LoicTheAztecLoicTheAztec

          94.2k1367107




          94.2k1367107

























              -1














              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






              share|improve this answer




























                -1














                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






                share|improve this answer


























                  -1












                  -1








                  -1







                  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






                  share|improve this answer













                  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







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 11 '18 at 18:14









                  RathnaRathna

                  24




                  24






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417670%2fwoocommerce-coupon-code-for-personalized-customer%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                      ComboBox Display Member on multiple fields

                      Is it possible to collect Nectar points via Trainline?