July 17, 2022: Added support for callable functions as coupon meta parameters.
July 22, 2021: Fixed an issue where scheduled coupons used GMT instead of the Time Zone configured in WordPress.
October 27, 2020: Migrated snippet to the Snippet Library.
Offering a coupon is a great way to incentivize users to fill out any form.
Want to provide a compelling incentive for visitors to sign up for your newsletter? Offer them a coupon code for a small discount at your shop.
Trying to spread the word about your online store? Offer customers a “Share this Product with a Friend” that will send that friend a discount to be used on their first purchase.
Note: We also provide a solution that integrates Gravity Forms natively with WooCommerce. Learn more about Gravity Shop Product Configurator.
Getting Started
Check requirements
- Make sure you have Gravity Forms installed and activated.
- Already have a license? Download Latest Gravity Forms
- Need a license? Buy Gravity Forms
- Make sure you have Gravity Forms installed and activated.
Install the snippet
- Copy and paste the entire snippet into your theme’s functions.php file.
Configure the snippet
- The basic configuration only requires that you specify the which form should be used to generate coupons (
form_id
), which field’s value should be used as the coupon code (source_field_id
), and thetype
andamount
of the coupon. - See the Usage Examples and available Parameters below.
- The basic configuration only requires that you specify the which form should be used to generate coupons (
Usage Examples
WooCommerce Coupon with Flat Discount, Applied to Cart
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'plugin' => 'wc',
'amount' => 10,
'type' => 'fixed_cart'
) );
Creates a flat $10 discount that applies to the entire cart. Whenever form ID 608 is submitted, the value of field ID 1 is used to create a new coupon.
WooCommerce Coupon with Percentage Discount, Applied to Cart
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'plugin' => 'wc',
'amount' => 10,
'type' => 'percent'
) );
Creates a 10% discount that applies to the entire cart.
WooCommerce Coupon with Percentage Discount, Applied to Specific Product(s)
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'plugin' => 'wc',
'amount' => 10,
'type' => 'percent_product',
'meta' => array(
'product_ids' => '123'
)
) );
Creates a 10% discount that applies to only to product ID 123.
WooCommerce Coupon with Start Date
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'plugin' => 'wc',
'amount' => 10,
'type' => 'percent_product',
'meta' => array(
'start_date' => '2020-12-20'
)
) );
Creates a 10% discount that can be used from December 20, 2020.
Stackable WooCommerce Coupon with Usage Limit and Expiration Date
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'plugin' => 'wc',
'amount' => 10,
'type' => 'fixed_cart',
'meta' => array(
'individual_use' => 'no',
'usage_limit' => 5,
'expiry_date' => '12/31/2014'
)
) );
Creates a flat $10 discount that applies to the entire cart. This coupon is can be used with other coupons (we set individual_use to 'no'
). The coupon can be used up to 5 times (handled by the usage_limit) and will expire on December 31, 2014 (via the expiry_date).
WooCommerce Coupon with Name Set by Field Value
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'name_field_id' => 20,
'plugin' => 'wc',
'amount' => 15,
'type' => 'fixed_cart',
) );
Creates a flat $15 discount that applies to the entire cart. This coupon’s title is derived from the value in field ID 20 (handled by name_field_id).
WooCommerce Coupon with Product IDs Set by Field Value
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'plugin' => 'wc',
'type' => 'fixed_product',
'amount' => 10,
'meta' => array(
'product_ids' => function() {
return rgpost( 'input_2' );
},
),
) );
Creates a flat $10 discount that applies to the total of all products passed in the product_ids
meta. The value of the product_ids
meta is set dynamically based on the value submitted in field ID 2.
Parameters
Here is a full list of the available parameters and additional information on how each can be configured.
new GW_Create_Coupon( array(
'form_id' => 608,
'source_field_id' => 1,
'name_field_id' => 20,
'plugin' => 'wc',
'amount' => 10,
'type' => 'fixed_cart', // accepts: 'fixed_cart', 'percent', 'fixed_product', 'percent_product'
'meta' => array(
'apply_before_tax' => 'no',
'customer_email' => '',
'exclude_product_categories' => array(),
'exclude_product_ids' => '',
'exclude_sale_items' => 'no',
'expiry_date' => '',
'free_shipping' => 'no',
'individual_use' => 'yes',
'limit_usage_per_customer' => '',
'limit_usage_to_x_items' => '',
'maximum_amount' => '',
'minimum_amount' => '',
'product_categories' => array(),
'product_ids' => '',
'start_date' => '', // YYYY-MM-DD,
'usage_limit' => 1
)
) );
form_id (integer) (required)
The ID of the form which will be used to create coupons on submission.
source_field_id (integer) (required)
The ID of the field whose value will be used as the coupon code.
name_field_id (integer) (optional)
The ID of the field whose value will be used as the coupon title.
plugin (string) (required)
The plugin for which you would like to generated a coupon. WooCommerce (
'wc'
), Easy Digital Downloads ('edd'
), and Gravity Forms ('gf'
) are currently supported.amount (integer|float) (required)
The amount the generated coupon should discount.
type (string) (required)
The type of coupon. Supported values are:
'fixed_cart'
Applies a flat discount to the entire cart. 'percent'
Applies a percentage discount to the entire cart. 'fixed_product'
Applies a flat discount to a specific product(s). 'percent_product'
Applies a percentage discount to a specific product(s). meta (array) (optional)
An array of additional options that can be used to customize the generated coupon.
individual_use Set to 'yes'
if the coupon cannot be used in conjunction with other coupons.product_ids A comma-delimited list of products (by ID) which need to be in the cart to use this coupon or, for “Product Discounts”, which products are discounted. exclude_product_ids A comma-delimited list of products (by ID) which must not be in the cart to use this coupon or, for “Product Discounts”, which products are not discounted. usage_limit Set how many times this coupon can be used before it is void. Default value is 1
. Set to''
for unlimited usage.expiry_date Specify the date when the coupon expires. Format: 'YYYY-MM-DD'
. Example:2014-09-30
start_date Specify the date when the coupon becomes active. Format: 'YYYY-MM-DD'
. Example:2014-09-30
apply_before_tax Set to 'yes'
if the coupon should be applied before calculating cart tax.free_shipping Set to 'yes'
if the coupon grants free shipping. The free shipping method must be enabled with the “must use coupon” setting.exclude_sale_items Set to 'yes'
if the coupon should not apply to items on sale.product_categories A product must be in this category (use category ID) for the coupon to remain valid or, for “Product Discounts”, products in these categories will be discounted. exclude_product_categories Product must not be in this category (use category ID) for the coupon to remain valid or, for “Product Discounts”, products in these categories will not be discounted. minimum_amount Set the minimum subtotal needed to use the coupon. maximum_amount Set the maximum subtotal allowed when using the coupon. customer_email Specify a list of emails to check against the customer’s billing email when an order is placed. Separate email addresses with commas. limit_usage_to_x_items Specify the maximum number of individual items this coupon can apply to when using product discounts. Leave blank to apply to all qualifying items in cart. limit_usage_per_user Specify how many times this coupon can be used by an invidual user. Uses billing email for guests, and user ID for logged in users.
* Parameter descriptions are modified versions of the default help tooltips available in the WooCommerce coupon edit page.
How’d we do?
If you use it and like it, let us know. We’d love to hear the different ways you found this code useful!
Did this resource help you do something awesome with Gravity Forms?
Then you'll absolutely love Gravity Perks; a suite of 47+ essential add-ons for Gravity Forms with support you can count on.
I already have Gravity Forms for a year but I didn’t know you could create coupons for WoCommerce. Good to know. Thanks :)
Hi David, how would set this up to create two coupons with one form?
Thanks Darren
Hi Darren, you can create another instance of the class for the same form. More deets: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Thanks for coming back so fast. Okay, so simply duplicate that portion and add it below, like:
Yup. :)
Thanks David, works perfectly. One more question if I may, Where do I enter the Coupons description?
Will make it easier to list only “Refer a Friend” coupons in the Admin.
I added ‘post_excerpt’
Hi David, I’m wondering if there is a way to make the date field “today’s date + 1.” In other words, I want the coupon to expire in 24 hours. Is this possible?
Try something like this:
'expiry_date' => date( 'm/d/Y', strtotime( '+1 day' ) ),
I am wanting to only restrict the 10% off coupon to the people who filled in the gravity form. If I am in the woocommerce cart and entered the GF coupon code, the cart changes the pricing accordingly. I want check that the email address the customer enters into woocommerce is one that was submitted to the GF that the code was generated from. I tried adding ‘customer_email’ => function_exists( ‘rgpost’ ) ? rgpost( ‘input_1’ ) : ” to the list of parameters in the ” new GW_Create_Coupon( array( ” but this didn’t seem to work when I tested it as the order went through with the discount applied when I used a different email address than the one I used in GF.
Can you share your exact code?
Hi, and thank you for the code.
I’m intending to use this snippet for a store with multiple vendors. So I suppose I need to change (‘post_author’ => 1) in line 168 with (current_user_id) or something like that ? Is it possible to let vendors through this form select the products ID by title (instead of inserting them by default in php) and pick the expiration date too by themselves ?
Thank you in advance !
Hi Amin, it is possible but it would require custom work that we’re not able to provide at this time.
Thank you for this code David.
Before we purchase the Perks bundle, can you tell me if it’s possible to display the coupon code in the confirmation message (and in the notification email) after the user submits the form/survey? I’m not sure how I would achieve this feat.
Thank you!
Regards. B
Since the coupon code is just a field on the form, you can use the field’s merge tag to output the coupon any place GF merge tags are supported (i.e. notifications and confirmations). :)
Hello,
Awesome job! Question, the issue I am running into is with my form I am using the product pricing field with the quantity. With that being said the “woocommerce” quantity doesn’t automatically update the GF quantity. This is affecting my coupons since woocommerce only see 1 item in the cart when there may be 5. My coupon in woocommerce is a product discount so it should apply to each product in the cart but it isn’t because it doesn’t recognize the GF quantity. I don’t get it because it updates the total properly. Will this code help me with this?
Hi Evie, no, this snippet just allows you to create a WooCommerce coupon based on a Gravity Forms submission. It’s more of a special incentive you can offer your users for submitting the form.
Is there a way to do a random string for the coupon code? I’m planning on hundreds of people using this form (it’s a survey) and I want them to each have their own coupon code. I use Smart Coupons to generate coupons, but I don’t see a way to tie into that.
Not sure how Smart Coupons works but if you’re already using GF, our GP Unique ID plugin integrates with this really well. Just add a Unique ID field to your form and set the field ID as the “source_field_id” parameter.
Love this code, although I can’t get it to work with multiple product ids, it creates a coupon code on submission but only adds one product to the code.
Can you help me in the right direction, this is part of the code that has the ids in it:
‘product_ids’ => ‘103’,’111′,’112′,’113′,’114′,’115′,’116′,’90’,’92’,’93’
It olny adds the first iD, the rest is ignored.
Thank you
Simple =)
Your id’s all need to be wrapped inside the same set of quotes.
‘product_ids’ => ‘103,111,112,113,114,115,116,90,92,93’
Hmmm.. now I feel slightly blond!! Good thing that I am!
That I haven’t figured that one out?!? I am using another code to add a fee to certain product ids, and that code uses the ‘ ‘, ‘ ‘.. so I just figured it would be the same for this.
Cheers for the solution, just tested and off course it works!
@Marieke, glad you were able to get this sorted. :)
@Phil, thanks for helping out!
Hi, this snippet looks great. But when I drop it into my functions.php file, I get this error: “Class ‘GW_Create_Coupon’ not found in /path/to/my/functions.php”
You can see here: http://projects.kemdev.com/
I just copied and pasted it directly from your example above. Any thoughts? Thanks!
Nevermind. I figured it out. Didn’t realize there was a whole slew of code I needed to add, not just the tiny little configuration snippet. Must get more coffee!
Awesome! Code hard. Coffee good. ;)
Hi David, first up thanks for your phenomenal and consistently helpful advice and snippets. Just wondering when the ‘Creating coupons for GF Coupons Add-on’ article might go live?
Hi Richie, should be ready in the next couple of weeks. :)
Can’t seem to find any way to get in touch with a pre-purchase question on your Perks package. I need to know if the Conditional Pricing plugin will work in conjunction with the Gravity Forms Product Add-Ons plugin and then allow Calculations using Merge Tags in order to apply a percentage based increase or decrease in total price based on a final selection in the form. Hope I’m making sense, and that this will work :) Please let me know, thanks!
Hi Neil, GP Conditional Pricing will allow you to create set prices per product depending on values entered on the field. It does not currently support percentage-based pricing but the price of a non-Calculation product field can be used in a Calculation field to create a modified price. If you’d like to send me a specific example of your pricing structure, I can confirm:
https://gravitywiz.com/have-a-question-about-gravity-perks/
This is awesome, thanks for the snippet. This works phenomenally with woocommerce but my client has recently decided to use an off-site offering for his ebook called revizzit so now I have to import those vouchers into my wordpress db and release them one per successful purchase. Still haven’t decided the best route to go yet…CPT or private table…but this gives me inspiration!
Thanks for the kinds words and happy to inspire. ;)
OK… Can we send this to multiple email addresses? So I send it to 10 email addresses to restrict the use of the 10 coupon codes. I also want to use this on ONE product…
Sure thing, Shawn. Here is an example of the parameters for such a configuration. Keep in mind, you’ll still need to update values to meet your exact needs.
http://pastie.org/9611392
In the meta parameter, we set the customer_email to comma-delimited list of emails to users who should be able to use this coupon. We set the limit_usage_per_customer to
1
so each user can only use it once. Lastly, we set the products_ids parameter to the product ID to which this coupon should apply.Since the coupon code itself will always be pulled from a Gravity Form field, you can use GF’s notifications to send the coupon (use the field’s merge tag to include it in the message) to the users who should receive it.
Hey David,
Another great snippet! I was actually just thinking about this exact thing the other day but for Easy Digital Downloads. It’d be great to see this snippet extended to EDD as well.
Excellent work as always.
Ren
Hey Ren, glad you like it. It actually already supports EDD and will detail the available parameters in an upcoming article. For now, here’s a quick example of how you can instantiate this plugin for EDD right now:
http://pastie.org/9608616#6
Ah, I see that. I overlooked that info earlier. Thanks for snippet on instantiating for EDD. I look forward to the EDD specific post.
Thanks for the code. Just one question. Can we restrict the coupon use to the user who was registering with the form? If so what is the correct way to set the coupon recipient ID to be the same user ID as the person whose user account is being created?
Thanks
Hi Farrel, you can restrict the coupon to a static email by setting the “customer_email” parameter to that static email. In your case, since you want to use the email that the user submitted with the form, you could try setting the “customer_email” parameter like so:
'customer_email' => function_exists( 'rgpost' ) ? rgpost( 'input_1' ) : ''
Replace the “1” in “input_1” with the ID of your email field. This will check the submitted content for that email and populate it as the value of the parameter.
I tried adding that parmaeter but I got this error: syntax error, unexpected ”customer_email” (T_CONSTANT_ENCAPSED_STRING), expecting ‘)’
The error was caused by a missing comma :) However, the restrict email to the email submitted in form is not applying to the coupon that is created and the ‘individual_use’ => ‘no’, is still generating a coupon that is not stackable.
Hey Sam, drop us a line via the support form and we’ll dig in. :)
Wanted to see if you got this sorted for Sam? I’d like to do the same thing: generate a coupon that’s locked to the submitter’s email. I assume the easiest is just to add the submitted email to the “Email restrictions” field of the coupon. But I’m not sure how to do that?