Limit to one applied coupon, removing other previous applied coupons in Woocommerce











up vote
1
down vote

favorite












I am making coupon dynamically to use user email as coupon but how can I restrict user to use only one coupon per cart. If use multiple auto removed the previous one from cart.



    add_filter ( 'woocommerce_get_shop_coupon_data', 'generate_coupons', 10, 2  );
function generate_coupons( $data, $code) {
global $wpdb, $woocommerce;
$vpm_options = get_option( 'vpm_email_coupon_option_name' ); // Array of All Options
$amount = $vpm_options['coupon_value_3']; // coupon_discount
$offer_type = $vpm_options['offer_type_2']; // Type: fixed_cart, percent, fixed_product, percent_product
//getting the coupon input value
if (filter_var($code, FILTER_VALIDATE_EMAIL) && email_exists( $code )) {
$code = $code ;
}else{
$code = '';
}
// Check if the coupon has already been created in the database
$sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1;", $code );
$coupon_id = $wpdb->get_var( $sql );

if ( empty( $coupon_id ) ) {
// Create a coupon with the properties you need
$data = array(
'discount_type' => $offer_type,
'coupon_amount' => $amount, // value
'product_ids' => array(),
'exclude_product_ids' => array(),
'usage_limit' => '',
'usage_limit_per_user' => '',//Limit
'limit_usage_to_x_items' => '',
'usage_count' => '',
'expiry_date' => '2020-12-31', // YYYY-MM-DD
);
// Save the coupon in the database
$coupon = array(
'post_title' => $code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon'
);
$new_coupon_id = wp_insert_post( $coupon );

// Write the $data values into postmeta table
foreach ($data as $key => $value) {
update_post_meta( $new_coupon_id, $key, $value );
}
//apply the coupon
$woocommerce->cart->add_discount( $code );
return $data;
}
}









share|improve this question




























    up vote
    1
    down vote

    favorite












    I am making coupon dynamically to use user email as coupon but how can I restrict user to use only one coupon per cart. If use multiple auto removed the previous one from cart.



        add_filter ( 'woocommerce_get_shop_coupon_data', 'generate_coupons', 10, 2  );
    function generate_coupons( $data, $code) {
    global $wpdb, $woocommerce;
    $vpm_options = get_option( 'vpm_email_coupon_option_name' ); // Array of All Options
    $amount = $vpm_options['coupon_value_3']; // coupon_discount
    $offer_type = $vpm_options['offer_type_2']; // Type: fixed_cart, percent, fixed_product, percent_product
    //getting the coupon input value
    if (filter_var($code, FILTER_VALIDATE_EMAIL) && email_exists( $code )) {
    $code = $code ;
    }else{
    $code = '';
    }
    // Check if the coupon has already been created in the database
    $sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1;", $code );
    $coupon_id = $wpdb->get_var( $sql );

    if ( empty( $coupon_id ) ) {
    // Create a coupon with the properties you need
    $data = array(
    'discount_type' => $offer_type,
    'coupon_amount' => $amount, // value
    'product_ids' => array(),
    'exclude_product_ids' => array(),
    'usage_limit' => '',
    'usage_limit_per_user' => '',//Limit
    'limit_usage_to_x_items' => '',
    'usage_count' => '',
    'expiry_date' => '2020-12-31', // YYYY-MM-DD
    );
    // Save the coupon in the database
    $coupon = array(
    'post_title' => $code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type' => 'shop_coupon'
    );
    $new_coupon_id = wp_insert_post( $coupon );

    // Write the $data values into postmeta table
    foreach ($data as $key => $value) {
    update_post_meta( $new_coupon_id, $key, $value );
    }
    //apply the coupon
    $woocommerce->cart->add_discount( $code );
    return $data;
    }
    }









    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I am making coupon dynamically to use user email as coupon but how can I restrict user to use only one coupon per cart. If use multiple auto removed the previous one from cart.



          add_filter ( 'woocommerce_get_shop_coupon_data', 'generate_coupons', 10, 2  );
      function generate_coupons( $data, $code) {
      global $wpdb, $woocommerce;
      $vpm_options = get_option( 'vpm_email_coupon_option_name' ); // Array of All Options
      $amount = $vpm_options['coupon_value_3']; // coupon_discount
      $offer_type = $vpm_options['offer_type_2']; // Type: fixed_cart, percent, fixed_product, percent_product
      //getting the coupon input value
      if (filter_var($code, FILTER_VALIDATE_EMAIL) && email_exists( $code )) {
      $code = $code ;
      }else{
      $code = '';
      }
      // Check if the coupon has already been created in the database
      $sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1;", $code );
      $coupon_id = $wpdb->get_var( $sql );

      if ( empty( $coupon_id ) ) {
      // Create a coupon with the properties you need
      $data = array(
      'discount_type' => $offer_type,
      'coupon_amount' => $amount, // value
      'product_ids' => array(),
      'exclude_product_ids' => array(),
      'usage_limit' => '',
      'usage_limit_per_user' => '',//Limit
      'limit_usage_to_x_items' => '',
      'usage_count' => '',
      'expiry_date' => '2020-12-31', // YYYY-MM-DD
      );
      // Save the coupon in the database
      $coupon = array(
      'post_title' => $code,
      'post_content' => '',
      'post_status' => 'publish',
      'post_author' => 1,
      'post_type' => 'shop_coupon'
      );
      $new_coupon_id = wp_insert_post( $coupon );

      // Write the $data values into postmeta table
      foreach ($data as $key => $value) {
      update_post_meta( $new_coupon_id, $key, $value );
      }
      //apply the coupon
      $woocommerce->cart->add_discount( $code );
      return $data;
      }
      }









      share|improve this question















      I am making coupon dynamically to use user email as coupon but how can I restrict user to use only one coupon per cart. If use multiple auto removed the previous one from cart.



          add_filter ( 'woocommerce_get_shop_coupon_data', 'generate_coupons', 10, 2  );
      function generate_coupons( $data, $code) {
      global $wpdb, $woocommerce;
      $vpm_options = get_option( 'vpm_email_coupon_option_name' ); // Array of All Options
      $amount = $vpm_options['coupon_value_3']; // coupon_discount
      $offer_type = $vpm_options['offer_type_2']; // Type: fixed_cart, percent, fixed_product, percent_product
      //getting the coupon input value
      if (filter_var($code, FILTER_VALIDATE_EMAIL) && email_exists( $code )) {
      $code = $code ;
      }else{
      $code = '';
      }
      // Check if the coupon has already been created in the database
      $sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1;", $code );
      $coupon_id = $wpdb->get_var( $sql );

      if ( empty( $coupon_id ) ) {
      // Create a coupon with the properties you need
      $data = array(
      'discount_type' => $offer_type,
      'coupon_amount' => $amount, // value
      'product_ids' => array(),
      'exclude_product_ids' => array(),
      'usage_limit' => '',
      'usage_limit_per_user' => '',//Limit
      'limit_usage_to_x_items' => '',
      'usage_count' => '',
      'expiry_date' => '2020-12-31', // YYYY-MM-DD
      );
      // Save the coupon in the database
      $coupon = array(
      'post_title' => $code,
      'post_content' => '',
      'post_status' => 'publish',
      'post_author' => 1,
      'post_type' => 'shop_coupon'
      );
      $new_coupon_id = wp_insert_post( $coupon );

      // Write the $data values into postmeta table
      foreach ($data as $key => $value) {
      update_post_meta( $new_coupon_id, $key, $value );
      }
      //apply the coupon
      $woocommerce->cart->add_discount( $code );
      return $data;
      }
      }






      php wordpress woocommerce cart coupon






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      LoicTheAztec

      77.9k125991




      77.9k125991










      asked 2 days ago









      Firefog

      1,22741641




      1,22741641
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          The following code will remove the first applied coupon, if customer applies another coupon code, so there will be only one applied coupon in cart (the last applied coupon):



          add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
          function one_applied_coupon_only( $cart ) {
          if ( is_admin() && ! defined( 'DOING_AJAX' ) )
          return;

          if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
          return;

          // For more than 1 applied coupons only
          if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
          // Remove the first applied coupon keeping only the last appield coupon
          $cart->remove_coupon( reset($coupons) );
          }
          }


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






          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',
            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%2f53238413%2flimit-to-one-applied-coupon-removing-other-previous-applied-coupons-in-woocomme%23new-answer', 'question_page');
            }
            );

            Post as a guest
































            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            The following code will remove the first applied coupon, if customer applies another coupon code, so there will be only one applied coupon in cart (the last applied coupon):



            add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
            function one_applied_coupon_only( $cart ) {
            if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;

            if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;

            // For more than 1 applied coupons only
            if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
            // Remove the first applied coupon keeping only the last appield coupon
            $cart->remove_coupon( reset($coupons) );
            }
            }


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






            share|improve this answer

























              up vote
              1
              down vote



              accepted










              The following code will remove the first applied coupon, if customer applies another coupon code, so there will be only one applied coupon in cart (the last applied coupon):



              add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
              function one_applied_coupon_only( $cart ) {
              if ( is_admin() && ! defined( 'DOING_AJAX' ) )
              return;

              if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
              return;

              // For more than 1 applied coupons only
              if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
              // Remove the first applied coupon keeping only the last appield coupon
              $cart->remove_coupon( reset($coupons) );
              }
              }


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






              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                The following code will remove the first applied coupon, if customer applies another coupon code, so there will be only one applied coupon in cart (the last applied coupon):



                add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
                function one_applied_coupon_only( $cart ) {
                if ( is_admin() && ! defined( 'DOING_AJAX' ) )
                return;

                if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
                return;

                // For more than 1 applied coupons only
                if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
                // Remove the first applied coupon keeping only the last appield coupon
                $cart->remove_coupon( reset($coupons) );
                }
                }


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






                share|improve this answer












                The following code will remove the first applied coupon, if customer applies another coupon code, so there will be only one applied coupon in cart (the last applied coupon):



                add_action( 'woocommerce_before_calculate_totals', 'one_applied_coupon_only', 10, 1 );
                function one_applied_coupon_only( $cart ) {
                if ( is_admin() && ! defined( 'DOING_AJAX' ) )
                return;

                if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
                return;

                // For more than 1 applied coupons only
                if ( sizeof($cart->get_applied_coupons()) > 1 && $coupons = $cart->get_applied_coupons() ){
                // Remove the first applied coupon keeping only the last appield coupon
                $cart->remove_coupon( reset($coupons) );
                }
                }


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







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered yesterday









                LoicTheAztec

                77.9k125991




                77.9k125991






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53238413%2flimit-to-one-applied-coupon-removing-other-previous-applied-coupons-in-woocomme%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest




















































































                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Error while running script in elastic search , gateway timeout

                    Adding quotations to stringified JSON object values