This post is made possible by yet another great Gravity Forms snippet from David Smith at GravityWiz.com, Creating Coupons for WooCommerce with Gravity Forms. This snippet integrates with WooCommerce, Easy Digital Downloads and Gravity Forms Coupons. I’ve modified the snippet specifically for Easy Digital Downloads and to allow for randomly generated codes and dynamic expiration dates.
This Gravity Forms tutorial is great for WordPress site-owners who want to reward their users after submitting a form. For example, Gravity Forms is great for creating email newsletter registration forms. It integrates with popular email services like MailChimp and Aweber. I’ll be writing this tutorial in the email-signup context. When a user signs up for our email list, we will give them a $10 discount code that can be used in our Easy Digital Downloads store.
Preliminaries
As this is a pretty involved process, let’s first outline our main goals.
- Create a newsletter registration form using the Gravity Forms plugin.
- Connect the form to a MailChimp account and enroll the submitter into an email list.
- When this newsletter registration form is submitted, generate a unique (not in use) discount code of $10 in value.
- The discount code should be random to prevent predictability and have a dynamic/relative expiration date.
- Finally, we’ll also include a direct link to automatically add a download of our choice (i.e. a top grosser) to the user’s shopping cart and apply the newly generated discount.
Sound fun? I know it does!
Also, I’m going to assume the following for this tutorial, meaning I won’t be explaining how to do these tasks:
- You have installed Gravity Forms and configured your basic settings.
- You have installed and configured the appropriate Gravity Forms addon to integrate GF with your email newsletter service of choice (MailChimp in this tutorial).
- You are comfortable with editing some PHP. You don’t need to know how to write it but you should be okay with navigating a PHP file and making very basic changes.
The Code
As I mentioned at the beginning of this post, we are going to be using a snippet that was written by David Smith of GravityWiz.com. If you have not seen GravityWiz and you use Gravity Forms for anything more than the most basic of contact forms, go take a look right now. If his content helps you, buy his Gravity Perks plugin. It’s got a lot of cool addons for extending Gravity Forms and I’m sure your contribution will help him to continue producing such awesome stuff! As a side note, I’m not affiliated with David or GravityWiz…I’m a big fan of David’s GF work and I can vouch for his expertise.
Here is my modified version of David’s code. It is specifically for creating discount codes for Easy Digital Downloads only. David’s original snippet also works for WooCommerce and Gravity Forms coupons so if you would like to use this concept for either of those, go grab his code as he wrote it. Additionally, I’ve added a couple modifications that will 1.) generate a discount code containing random characters (based on another snippet of David’s) and 2.) utilize dynamic start/expiration dates.
Now we need to configure this code so here’s where you need to be minimally comfortable with editing PHP. I’ve outlined exactly what you need to do so you shouldn’t have any trouble.
- On line 24 (required), replace 3 with the ID of the form that you are using to generate the discount code.
- On line 25 (required), replace 4 with the ID of the field that will hold the actual discount code.
- On line 26 (optional), replace 12 with the character length you wish your codes to be.
- On line 27 (optional), the discount code will consist of these characters: numbers 0-9 and capital letters.
- On line 28 (optional), you can enter a prefix for the discount code.
- On line 29 (optional), you can define the type of discount: flat discount (default) or percentage.
- On line 30 (optional), replace 10 with the value of the discounts to be created. This number will be paired with the discount type to determine the actual discount ($10 by default).
- On line 31 (optional), replace 1 with the maximum number of times a single customer can use the discount. The value for line 35 must be set to false for this setting to apply.
- On line 32 (optional), remove the single quotes and replace with an integer for a minimum amount required in the user’s cart before the discount can be applied.
- On line 33 (optional), enter a comma-separated list of product IDs for which the discounts will apply to. Use this setting OR line 36 but do not use both.
- On line 34 (optional), define how the the coupon will apply when these products are in the cart. If ‘any’, the coupon will work as long as one of the product’s is in the cart. If ‘all’, the discount will only be applied if all the product IDs listed on line 33 are in the cart.
- On line 35 (optional), define whether the discount can be used more than once by a single customer. The default setting is ‘use_once’ but can be set to false (boolean) for allowing users to use it more than once. The number of times it can be used it determined by the value on line 31.
- On line 36 (optional), enter a comma-separated list of product IDs for which the discounts will NOT apply to. Use this setting OR line 33 but do not use both.
- On lines 49 and 53 (optional) are the dates for activating and expiring your discount. I’m not sure how these dates are formatted in EDD for other countries but, in the U.S., it uses the mm/dd/yyyy format. You can change it to the format you need, if necessary. See here for PHP date formats. For my purposes, I don’t need to have a start date because it will start as soon as it’s created. However, I do want an expiration date so the $exp_date is set for +30 days, resulting in a lifespan of 30 days for the coupons generated. You can change this to whatever you’d like.
I’ve taken steps to prevent you from needing to edit code beyond line 55 so, once you’ve edited the required and optional lines, you’re done. You can add the configured code into your theme’s functions.php or zip it up and add it as a plugin (this is the method I recommend).
Editing the Signup Form
As mentioned previously, I am assuming you have created a form and integrated it with the newsletter service of your choice. At the very minimum, this form needs to contain an email field. Personally, I also like to collect a first and last name so my form, currently, has three fields.
To get the Easy Digital Downloads configuration set up properly, we need to add a field to our form that will hold the discount code. To do this, add a “Hidden” field (from under the Standard Fields group) to your form and name it something like “Discount Code”. Under the Advanced tab for this new, hidden field, enable the “Allow field to be populated dynamically” option and enter uuid for the parameter name. Once you’ve got that, your form should look something like this:
Create a Confirmation and/or Notification
Almost there! Now we need to create a way to present the user with his or her newly minted discount code. The easiest way is to create a simple text confirmation using your own message and a couple Gravity Forms merge tags. You can get fancy with the confirmation and/or add an email notification for the code to be sent to your customer for later use. For what I want, I’m going to create a simple text confirmation but I’ll spice it up by including a link that will add a specific download to the user’s cart and automatically apply the discount that was generated when the form was submitted.
For my confirmation, I have the following HTML and merge tags:
Hi {FNAME:2}, Thanks for signing up! Here is your discount code and link: Discount Code: <span class="bold">{Discount Code:4}</span> <a href="http://yourdomain.com/checkout/?edd_action=add_to_cart&download_id=1807&discount={Discount Code:4}" class="action-button primary">Checkout w/ Discount</a>
This confirmation is using the {FNAME:2} merge tag, which is the admin label I gave to the First Name field and the field ID, 2. The other merge tag is {Discount Code:4}, the title and ID for the hidden field I created to hold the discount code. It is used to display the discount for copying/pasting and it is also passed into my Easy Digital Downloads add-to-cart link to apply the code on redirect. Now, after my form is submitted, this is what the user is shown:
Testing
At this point, all the work is finished. Now, all that’s left to do is test. Create a new page, insert your form and run a test submission. You should receive a message like the one above. It should display the discount code and any other text and/or merge tags you added. Next, check to confirm that your discount code was registered in Easy Digital Downloads. If it appears in the EDD Discount Codes section, you’ve successfully configured everything. Finally, click the link in the confirmation if you inserted one like I did or add a download to your cart and apply the discount by copying and pasting it into the EDD discount field on the checkout page. If it’s registered in EDD, it will work but you’ll want to confirm this just for the excitement of SEEING it work!
Wrapping Up
There you have it. You now have a system for rewarding your customers with a discount code to your Easy Digital Downloads store after they submit a form. If you have any questions, feel free to drop a comment below and I’ll do my best to help you out. You can also leave a comment for David here.
Noah says
Thanks so much for providing this great tutorial!!
What would be your recommended way to make the discount amount dynamically defined based on a field value from the gravity form? Could you set the constant to a variable, such as: define( ‘ENGWP_DISCOUNT_AMOUNT’, $amount ) and then set $amount to = the value of a form field?
The idea is to just repurpose this to allow people to purchase coupons as gifts.
Mohammad says
Hi Ren!
Excellent article! I love Gravity Forms and it’s amazing what you and others like you have come up with! I was looking for almost this exact solution for a project I’m working on. Mine, however, is dependent on Woocommerce and not EDD. David’s original article obviously was about Woocommerce, but it was about how the coupons was applied to the cart and not a form submission. Yours is the solution I’m looking for but for Woocommerce. How can I take what you did and apply it to Woocommerce?
Thanks again for providing this awesome solution.
Ren says
Hi Mohammed,
Maybe I’m not following entirely, but if you take a closer look at David’s code, you should see that it handles creating discounts in WooCommerce.
/**
* Create a WooCommerce coupon.
*
* @link https://gist.github.com/mikejolley/3969579#file-gistfile1-txt
*/
public function create_coupon_wc( $coupon_code, $amount, $type ) {
$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 );
$meta = wp_parse_args( $this->_args[‘meta’], array(
‘discount_type’ => $type,
‘coupon_amount’ => $amount,
‘individual_use’ => ‘yes’,
‘product_ids’ => ”,
‘exclude_product_ids’ => ”,
‘usage_limit’ => ‘1’,
‘expiry_date’ => ”,
‘apply_before_tax’ => ‘no’,
‘free_shipping’ => ‘no’,
‘exclude_sale_items’ => ‘no’,
‘product_categories’ => ”,
‘exclude_product_categories’ => ”,
‘minimum_amount’ => ”,
‘customer_email’ => ”
) );
foreach( $meta as $meta_key => $meta_value ) {
update_post_meta( $new_coupon_id, $meta_key, $meta_value );
}
}
That code creates the discount code in WooCommerce. If you need to have the discount apply to specific products rather than the entire cart, David provides an example instantiation:
new GW_Create_Coupon( array(
‘form_id’ => 608,
‘source_field_id’ => 1,
‘plugin’ => ‘wc’,
‘amount’ => 10,
‘type’ => ‘percent_product’,
‘meta’ => array(
‘product_ids’ => ‘123’
)
) );
Hopefully that helps.
nikunj says
Thanks….
dano says
Hi!
Iยดm looking for a way to attach a individual coupon code to a Aweber optin form that would let me send out individual codes to every subscriber. Any idea how to accomplish that?
Ren says
Hey, dano. If I’m understanding correctly, you basically want to send a discount code to every member of an Aweber list?
If I’m correct in my understanding, I don’t think it can be done via Aweber, or any other newsletter service for that matter. The reason is because services like Aweber, Mailchimp, etc., are for creating relatively static newsletter emails. The dynamic data that can be used in these emails is limited to list data stored about the user, such as name and email. This information is stored by the provider, not by you.
The email you described involves dynamic data that is much more significant because it requires interaction with your WordPress installation. Essentially, a user interacts with your site, an action is taken, your website registers a code, then the user receives an email with that code. This is typically referred to as a “transactional” email because it is specific to the user, rather than a generalized “newsletter” email.
All that said, it’s still possible to do. I’m more familiar with Mailchimp, but I know that Aweber has an API that you can use to retrieve your subscribers. This is what you’d use to pull your subscribers, then you’d use WordPress functionality to send the emails.
Because this needs to be done on the WordPress side, I recommend using a service like Mandrill if you’re going to be constantly sending emails from your website.
Hopefully that helps. If I was misunderstanding your question, please clarify and I’ll update you as best I can.
Bowe Frankema says
Hey Ren,
Awesome idea and I’ve almost got it working. Have you updated the code by any chance because I’m running into a a “Product requirements are not met” error.. Here’s the function that generates that: http://edd.wp-a2z.org/oik_api/edd_discount_product_reqs_met/
I’m not sure why this is happening but it seems some meta data is missing/added that causes issues with creating valid coupons?
Here’s my config:
https://gist.github.com/BoweFrankema/9c94f060d03098771265
Thanks in advance for any help ๐
Ren says
Hey, Bowe. I just checked the functionality of the code and everything is working straight for me. Did you make any modifications to the class? To get the error you mentioned, there would need to be at least one product requirement for the discount code and, by default, the class doesn’t add any.
Add this code to your theme’s functions.php:
This will verify whether there have been any product requirements added to the discount. By default, it should be an empty array (no requirements). It’s only when there are requirements that the code can enter the switch statement that produces that error.
Bowe Frankema says
Hi Ren!
Sorry for the late reply, for some reason I never received a notification of your reply. When I add your code to my functions php the following is printed for a newly generated discount coupon:
Array
(
[0] =>
)
So you’re saying it should return nothing? Thanks for your help on this!
Bowe Frankema says
After some more digging around I’ve decided to simply remove all the unneeded arguments across the plugin (required products etc). The coupons now work as expected. It’s not an elegant solution but at least it’s working ๐
David Smith says
Good stuff, Ren! Let me know if any one reports bugs with the core code and I’ll make sure they get updated on my end as well. ๐
Ren says
Hey, David. Will do!