Automatically Send New Email Subscribers an EDD Discount Code

This tutorial uses ActiveCampaign and Easy Digital Downloads. It can probably be achieved with other platforms, but my guide doesn’t reflect that.

On my new Novelist plugin website I wanted to send all new email subscribers a 10% off coupon code as a thank you for signing up.

The easy way to do this in Easy Digital Downloads is to create a new discount code that never expires and doesn’t have a use limit. Then send everyone the same discount code in your welcome email.

…But I didn’t want to do that.

Obviously there are problems with this method. The code isn’t unique and doesn’t have any usage limits, so it can easily be reused, shared with friends, and so on.

My Goal

  • When a new person subscribes, trigger the code.
  • Create a unique discount code specifically for this person. The code has one use only.
  • Email that code to the new subscriber.

Step 1: Set up a new webhook in ActiveCampaign.

Go to “Automations” and create a new automation.

ActiveCampaign webhook automation

The trigger can be anything you want. I chose when someone subscribes to my blog post mailing list.

For your action, look under “Conditions & Workflow” and select “Webhook”. For the URL, enter this:

http://yoursite.com/?trigger-special-discount=true&discount-key=JkbYRHvWAoddmVUTK1u8RH8V

I’ve highlighted the stuff you need to change.

  • Replace yoursite.com with your actual site URL where Easy Digital Downloads is installed.
  • Replace JkbYRHvWAoddmVUTK1u8RH8V with a random string of numbers and letters. This is kind of like a password to help make sure that not just anyone can send stuff to this URL and trigger discount codes.

Step 2: Coding the WordPress plugin.

Now we create a WordPress plugin to actually listen at that URL and create the discount code.

Here’s the header for our file containing the plugin name and other information:

<?php
/**
 * Plugin Name: EDD - Discounts for Subscribers
 * Plugin URI: https://www.nosegraze.com
 * Description: Automatically email a discount code to new subscribers.
 * Version: 1.0
 * Author: Nose Graze
 * Author URI: https://www.nosegraze.com
 * License: GPL2
 * 
 * @package edd-discounts-subscribers
 * @copyright Copyright (c) 2016, Nose Graze Ltd.
 * @license GPL2+
*/

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

And here’s the actual function that makes the magic happen:

/**
 * Create and send 10% off coupon code when signing up for mailing list.
 *
 * @return void
 */
function ng_edd_discounts_subscribers_send_code() {
	if ( ! isset( $_GET['trigger-special-discount'] ) || ! isset( $_GET['discount-key'] ) || $_GET['discount-key'] != 'JkbYRHvWAoddmVUTK1u8RH8V' || ! function_exists( 'edd_store_discount' ) ) {
		return;
	}

	// Now check to make sure we got data from AC.
	if ( ! isset( $_POST['contact'] ) || ! isset( $_POST['contact']['email'] ) ) {
		return;
	}

	$contact = $_POST['contact'];
	$email   = wp_strip_all_tags( $contact['email'] );

	if ( ! is_email( $email ) ) {
		return;
	}

	global $wpdb;
	$discount_name = sprintf( '10%% off for %s', $email );

	$query   = "
        SELECT      *
        FROM        $wpdb->posts
        WHERE       $wpdb->posts.post_title LIKE '$discount_name%'
        AND         $wpdb->posts.post_type = 'edd_discount'
        ORDER BY    $wpdb->posts.post_title
";
	$results = $wpdb->get_results( $query );

	// Already created a discount for this email.
	if ( is_array( $results ) && count( $results ) ) {
		return;
	}

	$timestamp     = time();
	$numbers_array = str_split( $timestamp . rand( 10, 99 ) );
	$letters_array = array_combine( range( 1, 26 ), range( 'a', 'z' ) );
	$final_code    = '';

	foreach ( $numbers_array as $key => $value ) {
		$final_code .= $letters_array[ $value ];
	}

	$discount_args = array(
		'code'     => $final_code,
		'name'     => $discount_name,
		'status'   => 'active',
		'max'      => 1,
		'amount'   => 10,
		'type'     => 'percent',
		'use_once' => true,
	);

	edd_store_discount( $discount_args );

	$first_name = ( array_key_exists( 'first_name', $contact ) && ! empty( $contact['first_name'] ) ) ? $contact['first_name'] : 'there';

	$message = sprintf(
		"<p>Hey %s!</p>
		<p>Thanks so much for signing up for my list. As a thank you, here's a 10%% off discount code you can use on your next purchase in my shop:</p>
		<p><strong>%s</strong></p>
		<p>Enter this code at checkout to remove 10%% from your total.</p>
		<p>Have a great day!</p>
		<p>- Your Name</p>",
		esc_html( $first_name ),
		esc_html( $final_code )
	);

	$headers = array(
		'Content-Type: text/html; charset=UTF-8',
		'From: Your Name <noreply@yourwebsite.com>'
	);

	wp_mail( $email, 'Nose Graze 10% off Discount', $message, $headers );
}

add_action( 'init', 'ng_edd_discounts_subscribers_send_code' );

You will need to edit a few things:

  1. Make sure you enter your actual random key here: $_GET['discount-key'] != 'JkbYRHvWAoddmVUTK1u8RH8V'. That should be the same as what you entered in the URL in the webhook.
  2. This line: $discount_name = sprintf( '10%% off for %s', $email ); is the name of the discount code inside EDD (for admin use only). You can change it if you want (particularly if you’re using a different percentage). Make sure you keep the two percent signs there. Only one will actually show up.
  3. You may choose to adjust some of the settings here:
    $discount_args = array(
    	'code'     => $final_code,
    	'name'     => $discount_name,
    	'status'   => 'active',
    	'max'      => 1,
    	'amount'   => 10,
    	'type'     => 'percent',
    	'use_once' => true,
    );
    • max is the maximum number of uses. I have it set to 1.
    • type can be 'percent' or 'flat'
    • amount is the discount number. I have it set to 10, which means 10% when combined with type.
    • use_once means it can only be used once per customer (if set to true).
  4. You can edit the actual welcome message here:
    $message = sprintf(
    	"<p>Hey %s!</p>
    	<p>Thanks so much for signing up for my list. As a thank you, here's a 10%% off discount code you can use on your next purchase in my shop:</p>
    	<p><strong>%s</strong></p>
    	<p>Enter this code at checkout to remove 10%% from your total.</p>
    	<p>Have a great day!</p>
    	<p>- Your Name</p>",
    	esc_html( $first_name ),
    	esc_html( $final_code )
    );

    Be careful with the quotes and whatnot.

  5. You’ll want to change the from name and email here: 'From: Your Name <noreply@yourwebsite.com>'
  6. And finally, the subject of the email here: '10% off Discount'

View the code on GitHub

Photo of Ashley
I'm a 30-something California girl living in England (I fell in love with a Brit!). My three great passions are: books, coding, and fitness. more »

Don't miss my next post!

Sign up to get my blog posts sent directly to your inbox (plus exclusive store discounts!).

You might like these

8 comments

  1. Great tutorial, thanks for sharing. I’ve been looking for a method to code the automated discounts for a while now.
    I haven’t fully tested this, but the same could be accomplished on Mailchimp. Your Step 1 would be replaced with Mailchimp’s steps for setting up a webhook, which can be found here http://kb.mailchimp.com/integrations/api-integrations/how-to-set-up-webhooks
    I believe the rest of your tutorial should be the same with respect to coding the integration on your site, etc.
    After I test it out I can comment back with any bumps I run into if any.

    1. The only changes that were necessary for this to work on Mailchimp were to the $_POST variables.

      if ( ! isset( $_POST[‘data’][‘merges’] ) ) {
      return;
      }

      $contact = $_POST[‘data’][‘merges’];
      $email = wp_strip_all_tags( $contact[‘EMAIL’] );

      and

      $first_name = ( array_key_exists( ‘FNAME’, $contact ) && ! empty( $contact[‘FNAME’] ) ) ? $contact[‘FNAME’] : ‘there’;

    2. Hi Ashley,
      I achieved this for any mailing company through thrive leads. Thrive leads provides Notification option to send notification for the new subscriber to admins through emails, custom scripts & WordPress notification. I just followed your tut and setup with thrive leads using Notification custom scripts. They need URL and I set up an URL like https://mysite.com/?emailwebhook=thriveleadscamp1. It posts all the necessary data that I can grab and followed your tut after that.

  2. Thanks Ashley!

    We rely on a third-party vendor for event registrations and needed a way to give registrants a free product. Perfect!

Recent Posts

    Random Posts