Create Commerce Coupon Programmatically


Create Commerce Coupon Programmatically

Get raw version
  1. function pre($_){
  2. echo '<pre>';
  3. print_r($_);
  4. echo '</pre>';
  5. }
  6. //Get coupon types
  7. pre($types = commerce_coupon_get_types());
  8. //Create Default Coupon Instance
  9. pre($coupon = commerce_coupon_create('commerce_coupon_pct'));
  10. //Generate unique "Coupon Code"
  11. $coupon_code = strtoupper(commerce_coupon_generate_coupon_code());
  12. //Fill Values
  13. $coupon->commerce_coupon_code[LANGUAGE_NONE][0]['value'] = $coupon_code;
  14. //Fill Additional Values if you use some other modules like ""
  15. $coupon->commerce_coupon_number_of_uses[LANGUAGE_NONE][0]['value'] = 999;
  16. $coupon->commerce_coupon_percent_amount[LANGUAGE_NONE][0]['value'] = 20;
  17. $coupon->commerce_coupon_per_user_check[LANGUAGE_NONE][0]['value'] = 1;
  18. $coupon->commerce_coupon_per_user_uses[LANGUAGE_NONE][0]['value'] = 1;
  19. //$coupon->commerce_coupon_per_user_allowed[LANGUAGE_NONE][0]['value'] = array();
  20. //Save new coupon
  21. pre(commerce_coupon_save($coupon));
  22. //Check Coupon
  23. pre($coupon = commerce_coupon_load_by_code($coupon_code));


waveer's picture

I use the above code and happen a problem
everytime I run these code , it will save two coupns to the database ?
Do someone know why ?

waveer's picture

  1. function generate_coupon(){
  2. $coupon = commerce_coupon_create('commerce_coupon_pct');
  3. $coupon->commerce_coupon_number_of_uses[LANGUAGE_NONE][0]['value'] = 1;
  4. $coupon->commerce_coupon_percent_amount[LANGUAGE_NONE][0]['value'] = 10;
  6. commerce_coupon_save($coupon);
  8. return $coupon->commerce_coupon_code[LANGUAGE_NONE][0]['value'];
  9. }
  11. function mymodule_init() {
  12. generate_coupon();
  13. }

The problem will be reappearred when you refresh a page, if you visit the page as the first time, it will works well, someone told me this is because the code has been run two times, but he don't tell me why, if you know why, please tell me, thanks!

Dustin's picture

I am trying to create a new coupon in code that also is referenced to a user, I don't see where in your code or in the db where this value for Recipient - discount coupon referenced entity?

anyone know how to change the user that a new coupon is only for.


inri13666's picture

@waveer if you wish to create only one coupon you need to place your code at module installation hook, but if you wish to check if coupon exists and if not exists create you need to have static coupon code

inri13666's picture

@dustin It's very hard to understand what you wish to do)) in my sample no linking to specific user and while we create the raw coupon it disallow us to select specific user, but if you will use additional modules for example "coupon_per_user" you need to fill the fields as described at this module(s)

Ant's picture

What version of Commerce coupon is this for?

Would be very helpful. Thank you