The use of Gravity Forms to implement a simple double opt-in method for any newsletter app. In this example I’m using Campaign Monitor. Currently Campaign Monitor has a simple double opt-in routine however this can (at the time of writing this) be switched on and off and no record is kept whether an email address went through single or double opt-in. As far as I’m aware and I’m no legal beagle is that for General Data Protection Regulation (GDPR) which will be enforced on 25 May 2018 is that consent must be given for the purpose of data processing which includes recording that consent was given. More about that legal stuff here: https://www.eugdpr.org/
Our set up will include four forms are:
Email Campaign – Sign up
Email Campaign – Double Opt In
Email Campaign – Unsubscribe
Email Campaign – Something has gone wrong!
The double opt-in process is fairly straight forward for a visitor.
- Enter an email address requesting to sign up to the newsletter.
- The address entered receives an email asking them to confirm the request and provides a unique link to process that request.
- The email address is passed to Campaign Monitor via API.
Step 1: Setting up Campaign Monitor.
Get your Campaign Monitor API key. Instructions here https://help.campaignmonitor.com/api-keys
Create a new single opt-in (no confirmation required) list, for this example I’m naming it “Opted-In Subscribers”.
Under “Unsubscribe settings” edit the “Redirect unsubscribers to your own confirmation page” and set to your yet to be created unsubscribe page and end the URL with /?verify=[verify]& entryid=[entryid]
Example:
https://www.YOURDOMAIN.com/unsubscribe/?verify=[verify]&entryid=[entryid]
Under “Custom fields” add a new text field named “”verify” and a new number field named “entryid”
Step 2: Setting up your website.
Pre requisites
You should have Gravity Forms https://www.gravityforms.com/ and the Gravity Forms Campaign Monitor Add-On https://www.gravityforms.com/add-ons/campaign-monitor/ installed.
The Forms
Copy this code into a text editor and save it as a .json file. ie double-opt-in.json
{"0":{"title":"Email Campaign - Sign up","description":"<h2 style=\"text-align: center;\">Subscribe to Our Emails<\/h2>\r\n<h3 style=\"text-align: center;\">Never miss out on our deals and offers again.<\/h3>\r\n","labelPlacement":"top_label","descriptionPlacement":"below","button":{"type":"text","text":"Submit","imageUrl":""},"fields":[{"type":"email","id":1,"label":"Email","adminLabel":"","isRequired":true,"size":"medium","errorMessage":"","inputs":null,"formId":1,"description":"","allowsPrepopulate":true,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"email","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","emailConfirmEnabled":false,"displayOnly":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false},{"type":"hidden","id":2,"label":"verify","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":1,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"displayOnly":""}],"version":"2.2.5","id":1,"useCurrentUserAsAuthor":true,"postContentTemplateEnabled":false,"postTitleTemplateEnabled":false,"postTitleTemplate":"","postContentTemplate":"","lastPageButton":null,"pagination":null,"firstPageCssClass":null,"subLabelPlacement":"below","cssClass":"","enableHoneypot":false,"enableAnimation":false,"save":{"enabled":false,"button":{"type":"link","text":"Save and Continue Later"}},"limitEntries":false,"limitEntriesCount":"","limitEntriesPeriod":"","limitEntriesMessage":"","scheduleForm":false,"scheduleStart":"","scheduleStartHour":"","scheduleStartMinute":"","scheduleStartAmpm":"","scheduleEnd":"","scheduleEndHour":"","scheduleEndMinute":"","scheduleEndAmpm":"","schedulePendingMessage":"","scheduleMessage":"","requireLogin":false,"requireLoginMessage":"","confirmations":[{"id":"5a5ccf52b533d","name":"Default Confirmation","isDefault":true,"type":"message","message":"<p style=\"text-align: center;\">Thanks for subscribing to updates from us regarding our fantastic range of products, offers and exclusive deals.\r\nWe\u2019re sending you an email to confirm you\u2019re happy to hear from us!<\/p>","url":"","pageId":0,"queryString":"","disableAutoformat":false,"conditionalLogic":[]}],"notifications":[{"isActive":true,"id":"5a5cd22284341","name":"Confirm Email Opt In","service":"wordpress","event":"form_submission","to":"1","toType":"field","bcc":"","subject":"Please confirm your YOUR-COMPANY-NAME email subscription","message":"Thanks for signing up to our emails. You've nearly finished setting up your email address ({Email:1}), we just need you to <a href=\"https:\/\/YOUR-COMPANY-SUBSCRIBE_URL?verify={verify:2}\">click here to confirm<\/a> you're happy to receive news of our offers and deals. It won't take a minute!\r\n\r\nLink not working? Try pasting this link into your browser:\r\nYOUR-COMPANY-SUBSCRIBE_URL?verify={verify:2}\r\n\r\nIf you didn't sign up for these emails then please ignore and you will not be subscribed.\r\n\r\nYOUR-COMPANY-NAME","from":"YOUR-COMPANY@EMAIL.COM","fromName":"YOUR-COMPANY-NAME","replyTo":"","routing":null,"conditionalLogic":null,"disableAutoformat":false}]},"1":{"title":"Email Campaign - Double Opt In","description":"","labelPlacement":"top_label","descriptionPlacement":"below","button":{"type":"text","text":"Join","imageUrl":"","conditionalLogic":null},"fields":[{"type":"email","id":1,"label":"Email","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":2,"description":"","allowsPrepopulate":true,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"email","visibility":"hidden","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","emailConfirmEnabled":false,"displayOnly":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false},{"type":"hidden","id":2,"label":"verify","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":2,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"displayOnly":""}],"version":"2.2.5.21","id":2,"useCurrentUserAsAuthor":true,"postContentTemplateEnabled":false,"postTitleTemplateEnabled":false,"postTitleTemplate":"","postContentTemplate":"","lastPageButton":null,"pagination":null,"firstPageCssClass":null,"subLabelPlacement":"below","cssClass":"","enableHoneypot":false,"enableAnimation":false,"save":{"enabled":false,"button":{"type":"link","text":"Save and Continue Later"}},"limitEntries":false,"limitEntriesCount":"","limitEntriesPeriod":"","limitEntriesMessage":"","scheduleForm":false,"scheduleStart":"","scheduleStartHour":"","scheduleStartMinute":"","scheduleStartAmpm":"","scheduleEnd":"","scheduleEndHour":"","scheduleEndMinute":"","scheduleEndAmpm":"","schedulePendingMessage":"","scheduleMessage":"","requireLogin":false,"requireLoginMessage":"","notifications":[],"confirmations":[{"id":"5a5c8f22ccb6b","name":"Default Confirmation","isDefault":true,"type":"message","message":"<p style=\"text-align: center;\">All done!<\/p>\r\n<p style=\"text-align: center;\">Thank you for joining our mailing list, you can now look forward to being one of the first to hear about exclusive deals and offers from us!<\/p>","url":"","pageId":0,"queryString":"","disableAutoformat":false,"conditionalLogic":[]}]},"2":{"title":"Email Campaign - Unsubscribe","description":"","labelPlacement":"top_label","descriptionPlacement":"below","button":{"type":"text","text":"Send Feedback","imageUrl":"","conditionalLogic":null},"fields":[{"type":"textarea","id":10,"label":"We're sorry to see you go \u2013 what could we have done better?","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":3,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","form_id":"","useRichTextEditor":false,"multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"displayOnly":""},{"type":"checkbox","id":11,"label":"Please could you let us know why you have left:","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","choices":[{"text":"Sending it to the wrong person","value":"Sending it to the wrong person","isSelected":false,"price":""},{"text":"We send too many emails","value":"We send too many emails","isSelected":false,"price":""},{"text":"Content not relevant","value":"Content not relevant","isSelected":false,"price":""},{"text":"Looks like spam","value":"Looks like spam","isSelected":false,"price":""},{"text":"Other","value":"Other","isSelected":false,"price":""}],"inputs":[{"id":"2.1","label":"Sending it to the wrong person","name":""},{"id":"2.2","label":"We send too many emails","name":""},{"id":"2.3","label":"Content not relevant","name":""},{"id":"2.4","label":"Looks like spam","name":""},{"id":"2.5","label":"Other","name":""}],"formId":3,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"hidden","noDuplicates":false,"defaultValue":"","conditionalLogic":"","productField":"","enablePrice":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"enableChoiceValue":false,"displayOnly":""},{"type":"text","id":1,"label":"Email","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":3,"description":"","allowsPrepopulate":true,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"entry_email","visibility":"hidden","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","enablePasswordInput":"","maxLength":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"displayOnly":""},{"type":"hidden","id":2,"label":"verify","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":3,"description":"","allowsPrepopulate":true,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"verify","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"displayOnly":""},{"type":"hidden","id":3,"label":"entryid","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":3,"description":"","allowsPrepopulate":true,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"entryid","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"displayOnly":""}],"version":"2.2.5","id":3,"useCurrentUserAsAuthor":true,"postContentTemplateEnabled":false,"postTitleTemplateEnabled":false,"postTitleTemplate":"","postContentTemplate":"","lastPageButton":null,"pagination":null,"firstPageCssClass":null,"subLabelPlacement":"below","cssClass":"","enableHoneypot":false,"enableAnimation":false,"save":{"enabled":false,"button":{"type":"link","text":"Save and Continue Later"}},"limitEntries":false,"limitEntriesCount":"","limitEntriesPeriod":"","limitEntriesMessage":"","scheduleForm":false,"scheduleStart":"","scheduleStartHour":"","scheduleStartMinute":"","scheduleStartAmpm":"","scheduleEnd":"","scheduleEndHour":"","scheduleEndMinute":"","scheduleEndAmpm":"","schedulePendingMessage":"","scheduleMessage":"","requireLogin":false,"requireLoginMessage":"","confirmations":[{"id":"5a60824774c05","name":"Default Confirmation","isDefault":true,"type":"message","message":"Thanks for your feedback, it's appreciated.","url":"","pageId":0,"queryString":"","disableAutoformat":false,"conditionalLogic":[]}],"notifications":[{"id":"5a60824774a2a","to":"{admin_email}","name":"Admin Notification","event":"form_submission","toType":"email","subject":"New submission from {form_title}","message":"{all_fields}","isActive":false}]},"3":{"title":"Email Campaign - Something has gone wrong!","description":"","labelPlacement":"top_label","descriptionPlacement":"below","button":{"type":"text","text":"Send Feedback","imageUrl":""},"fields":[{"type":"textarea","id":10,"label":"Can you help by saying what you did","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":4,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","form_id":"","useRichTextEditor":false,"multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"displayOnly":""},{"type":"email","id":1,"label":"Email","adminLabel":"","isRequired":true,"size":"medium","errorMessage":"","inputs":null,"formId":4,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","emailConfirmEnabled":"","displayOnly":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false},{"type":"hidden","id":2,"label":"verify","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":4,"description":"","allowsPrepopulate":true,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"verify","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"displayOnly":""}],"version":"2.2.5","id":4,"useCurrentUserAsAuthor":true,"postContentTemplateEnabled":false,"postTitleTemplateEnabled":false,"postTitleTemplate":"","postContentTemplate":"","lastPageButton":null,"pagination":null,"firstPageCssClass":null,"subLabelPlacement":"below","cssClass":"","enableHoneypot":false,"enableAnimation":false,"save":{"enabled":false,"button":{"type":"link","text":"Save and Continue Later"}},"limitEntries":false,"limitEntriesCount":"","limitEntriesPeriod":"","limitEntriesMessage":"","scheduleForm":false,"scheduleStart":"","scheduleStartHour":"","scheduleStartMinute":"","scheduleStartAmpm":"","scheduleEnd":"","scheduleEndHour":"","scheduleEndMinute":"","scheduleEndAmpm":"","schedulePendingMessage":"","scheduleMessage":"","requireLogin":false,"requireLoginMessage":"","is_active":"1","date_created":"2018-01-19 15:16:43","is_trash":"0","confirmations":[{"id":"5a620bdb4c4fa","name":"Default Confirmation","isDefault":true,"type":"message","message":"Thanks for your feedback. One of our team will look into this.","url":"","pageId":0,"queryString":"","disableAutoformat":false,"conditionalLogic":[]}],"notifications":[{"isActive":true,"id":"5a620bdb4c247","name":"Admin Notification","service":"wordpress","event":"form_submission","to":"{admin_email}","toType":"email","bcc":"","subject":"New submission from {form_title}","message":"{all_fields}","from":"{admin_email}","fromName":"","replyTo":"","routing":null,"conditionalLogic":null,"disableAutoformat":false}]},"version":"2.2.5.21"}
On the code that you have just saved, conduct a find and replace on the following:
Find “YOUR-COMPANY-NAME” and replace with the from name for the emails sent to end users
Find “YOUR-COMPANY@EMAIL.COM” and replace with the public facing email address
Find “YOUR-COMPANY-SUBSCRIBE_URL” and replace you’re your yet to be created subscribe page ie www.YOURDOMAIN.com/subscribe/
Once that’s done save the file and then import as follows: goto Gravity forms > Import/Export and import your new file double-opt-in.json
This will create the four forms required.
Step 3. Connect the API.
Goto Forms > Settings > Campaign Monitor and enter the API Key that you got earlier.
Goto the form “Email Campaign – Double Opt In” settings > Campaign Monitor and add a new feed.
Choose “Opted-In Subscribers” from the drop down
Map the following:
Email Address > Email
Verify > verify
Entryid > Entry ID
Tick the resubscribe option
Step 4. Check the Forms.
Goto the form “Email Campaign – Sign up” settings and make sure your happy with the text that you are going to send out to the people who sign up. I’d recommend adding your company address to the “Confirm Email Opt In” notification email.
Step 5. Website Pages.
Create a new page called “Subscribe”
Add the shortcode:
[campaign_email_confirmed]Thanks for Joining [/campaign_email_confirmed]
Between these shortcodes you could display an image or a promo code etc.
It’s what will be displayed once a user has clicked the link in their email to confirm the subscription.
Create a new page called “Unsubscribe”
Add the text and shortcode :
You have successfully unsubscribed.
[campaign_email_unsubscribe]
Step 6. Functions file.
Copy the following code to your favourite text editor and conduct a find and replace:
Find “Form-A” and replace with the ID number of the form – “Email Campaign – Sign up”
Find “Form-B and replace with the ID number of the form – “Email Campaign – Double Opt In”
Find “Form-C” and replace with the ID number of the form – “Email Campaign – Unsubscribe”
Find “Form-D” and replace with the ID number of the form – “Email Campaign – Something has gone wrong!
Find “Key-A” and replace with a secret code ie FGFG£$%&FGH$334445e4
Find “Key-B” and replace with a secret code ie 740345445
functions.php
/**
* Version: 1.0
* Date: 08/02/2018
* Source: https://deanandrews.uk/wordpress-email-double-opt-gdpr-using-gravity-forms/
*
* Note:
* This code is provided "as is" and any expressed or implied warranties, including, but not limited to, the implied
* warranties of merchantability and fitness for a particular purpose are disclaimed.
* In no event shall the regents or contributors be liable for any direct, indirect, incidental, special, exemplary, or
* consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or
* profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or
* tort (including negligence or otherwise) arising in any way out of the use of this code, even if advised of
* the possibility of such damage.
*
* Use find and replace on this section of code
* Replace Form-A with the ID number of the form - Email Campaign - Sign up
* Replace Form-B with the ID number of the form - Email Campaign - Double Opt In
* Replace Form-C with the ID number of the form - Email Campaign - Unsubscribe
* Replace Form-D with the ID number of the form - Email Campaign - Something has gone wrong!
* Replace Key-A with a secret code ie FGFG£$%&FGH$334445e4
* Replace Key-B with a secret code ie 740345445
*/
/**********************************/
/* Gravity Form */
/*START double opt in procedure */
/**********************************/
* This checks the address that the user has entered in the Email Campaign - Sign up form
* It test if the email address has already been added via Email Campaign - Double Opt In
* If the address is found then it throws a custom validation message
*/
add_filter( 'gform_field_validation_Form-A_1', 'gf_custom_validation', 10, 4 );
function gf_custom_validation( $result, $value, $form, $field ) {
if ( $result['is_valid'] ) {
// check if it has already double opted in by counting the number of matching entries via the shortcode gravity_count_records
$field_input_count = do_shortcode('[gravity_count_records form_id="Form-B" field_id="1" search_for="' . $value . '"]');
if ( $field_input_count > 0 ) {
$result['is_valid'] = false;
$result['message'] = "It looks like the address " . $value . " is already registered to receive our emails";
}
}
return $result;
}
// On the Email Campaign - Sign up we take the email address and use a simple encrypt to disguise the fact that it's an email address and call it verify
add_action( 'gform_pre_submission_Form-A', 'gf_pre_submission_handler_Form-A' );
function gf_pre_submission_handler_Form-A( $form ) {
$_POST['input_2'] = custom_email_crypt(rgpost( 'input_1' ),'encrypt');
}
// Simple encrypt and decrypt email address to send as links in emails
function custom_email_crypt( $entry_email, $action = 'encrypt' ) {
// you may change these values to your own
$secret_key = 'Key-A';
$secret_iv = 'Key-B';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'encrypt' ) {
$entry_email = strtolower($entry_email);
$entry_email = trim($entry_email);
$output = base64_encode( openssl_encrypt( $entry_email, $encrypt_method, $key, 0, $iv ) );
$output .= "94a";//adding charater to end of url to ensure that if the resulting string ends with an = sign this doesn't get cut in the plain text version
}
else if( $action == 'decrypt' ){
$entry_email = substr($entry_email, 0, -3);// remove the last 3 char before decrypt
$output = openssl_decrypt( base64_decode( $entry_email ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
/**
* Add Shortcode to check if an email address has already been added via Email Campaign - Double Opt In
* It returns a number, which relates to the number of time it has found the entry even if it's in the Bin!
* example: [gravity_count_records form_id="Form-A" field_id="1" search_for="name@example.com"]
*/
function gf_count_records( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'form_id' => '9999',
'field_id' => '0',
'search_for' => '0',
),
$atts
);
$search_criteria['field_filters'][] = array( 'key' => $atts['field_id'], 'value' => $atts['search_for'] );
$countentries = GFAPI::count_entries($atts['form_id'], $search_criteria);
return $countentries;
}
add_shortcode( 'gravity_count_records', 'gf_count_records' );
/**
* Add Shortcode to Manually create Email Campaign - Sign up entries and send notifications
* this can be used on checkout or on another form to join our mailing list etc.
* example: [send_campaign_join_email email_address="name@example.com"]
*/
function gf_campaign_join_email( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'email_address' => '',
),
$atts
);
$entry_email = $atts['email_address'];
$entry_verify = custom_email_crypt($entry_email,'encrypt');
$form_id = Form-A;
// Chect that the email address is vaid
if (filter_var($entry_email, FILTER_VALIDATE_EMAIL)) {
//check to ensure that email has not already double opted in
$entry_email_count = do_shortcode('[gravity_count_records form_id="Form-B" field_id="1" search_for="' . $entry_email . '"]');
if ( $entry_email_count == 0 ) {
// add entry
$entry = array(
"form_id" => $form_id,
"1" => $entry_email,
"2" => $entry_verify
);
$entry_id = GFAPI::add_entry($entry);
// Get the array info for our forms and entries
// that we need to send notifications for
$form = RGFormsModel::get_form_meta($form_id);
$entry = RGFormsModel::get_lead($entry_id);
// Loop through all the notifications for the
// form so we know which ones to send
$notification_ids = array();
foreach($form['notifications'] as $id => $info){
array_push($notification_ids, $id);
}
// Send the notifications
GFCommon::send_notifications($notification_ids, $form, $entry);
// debug: return $entry_email . " " . $entry_verify . " " . $entry_verify . " " . $form_id;
}
}
}
add_shortcode( 'send_campaign_join_email', 'gf_campaign_join_email' );
/**
* Add Shortcode to Manually create entries and send to Campaign Monitor
* this is used as a shortcode on the subscribe page of the site
* example: [campaign_email_confirmed] SUCCESS CONTENT [/campaign_email_confirmed]
* in the subscribe page url the following are collected verify
*/
function gf_campaign_email_confirmed($atts , $content = null) {
$entry_verify = trim($_GET['verify']);
$entry_email = custom_email_crypt($entry_verify,'decrypt');
$form_id = Form-B;
// Chect that the email address is vaid
if (filter_var($entry_email, FILTER_VALIDATE_EMAIL)) {
//check to ensure that email has not already double opted in
$entry_email_count = do_shortcode('[gravity_count_records form_id="Form-B" field_id="1" search_for="' . $entry_email . '"]');
if ( $entry_email_count == 0 ) {
// add entry
$entry = array(
"form_id" => $form_id,
"1" => $entry_email,
"2" => $entry_verify
);
$entry_id = GFAPI::add_entry($entry);
// Get the array info for our forms and entries
// that we need to send notifications for
$form = RGFormsModel::get_form_meta($form_id);
$entry = RGFormsModel::get_lead($entry_id);
if (function_exists('gf_campaignmonitor')) {
$addon = gf_campaignmonitor();
if (method_exists($addon, 'maybe_process_feed')) {
$addon->maybe_process_feed($entry, $form);
}
}
// we are all good
return $content;
}else{
// Email found to be registered
return "It looks like the address " . $entry_email . " is already registered to receive our emails.";
}
}else{
if ($entry_verify == "new"){
//a new signup
return do_shortcode('[gravityform id="Form-A" title="false" description="true"]');
}else{
//something else went wrong as the email is not valid so dispaly a feedback form
return do_shortcode('[gravityform id="Form-D" title="true" description="false"]');
}
}
}
add_shortcode( 'campaign_email_confirmed', 'gf_campaign_email_confirmed' );
/**
* Add Shortcode to Manually delete entries in the double optin form db
* this is used as a shortcode on the unsubscribe page of the site
* example: [campaign_email_unsubscribe]
* in the unsubscribe page url the following are collected entryid
*/
function gf_campaign_email_unsubscribe() {
$entry_id = trim($_GET['entryid']);
$verify_id = trim($_GET['verify']);
$entry_email = custom_email_crypt($verify_id,'decrypt');
$form_id = Form-B;
// Test the inputs
if (filter_var($entry_email, FILTER_VALIDATE_EMAIL)) {
//check to ensure that email is double opted in
$entry_email_count = do_shortcode('[gravity_count_records form_id="Form-B" field_id="1" search_for="' . $entry_email . '"]');
if ( $entry_email_count > 0 ) {
// delete entry
$entry = array(
"form_id" => $form_id,
"entry_id" => $entry_id
);
$result = GFAPI::delete_entry( $entry_id );
}
//return $form_id . " " . $entry_id;
return gravity_form( Form-C, $display_title = false, $display_description = false, $display_inactive = false, $field_values = array('entry_email' => $entry_email), $ajax = false, $tabindex, $echo = true );
}
}
add_shortcode( 'campaign_email_unsubscribe', 'gf_campaign_email_unsubscribe' );
/**********************************/
/* Gravity Form */
/* END double opt in procedure */
/**********************************/
Once you have completed the find and replace copy the code block into your functions.php file (hopefully in your child theme :)).
Step 7. Htaccess or any form of redirect.
#Email new subscriber
redirect 302 /email-signup https://www.YOURDOMAIN.com/subscribe/?verify=new
In Use
Subscribing
You can direct your visitors to the URL https://www.YOURDOMAIN.com/email-signup
and they will be presented with a form to enter their email address. You could also use a pop-up method on the “Sign up” form.
Once the email address is submitted one of the following will happen:
If the email address is new or has not been through the double opt-in process then a message will be displayed to the user “Thanks for subscribing” etc. then a email will be sent to the address with the confirmation link.
If the email address has already been through the double opt-in process then a message will be given to say the address is already registered.
An email address will be sent to the given email address with the confirmation link. If the user ignores the email then no further action will be taken.
If the user clicks on the confirmation link they will be taken to your website subscribe page https://www.YOURDOMAIN.com/subscribe/?verify=bsdgsdFHDR32452325DRFUhIK1hLWT0=80x
The “Thanks for joining message” will be displayed or any image/copy that you have entered between the [campaign_email_confirmed]
short codes.
If the confirmation link is clicked again or the page refreshed then a message is displayed stating that the address is already registered to receive emails.
If the confirmation link is malformed then the “Something has gone wrong!” form will be displayed for the user to provide feedback.
Unsubscribing
Unsubscribing will use the standard method of one click unsubscribe as implemented by Campaign Monitor. However once a user unsubscribes they will be redirected to the unsubscribe page set up earlier with the following link:
https://www.YOURDOMAIN.com/unsubscribe/?verify=[verify]&entryid=[entryid]
the verify will be the confirmation link they used to signup and the entryid is the entry number of the form “Email Campaign – Double Opt In”.
When the user lands on the unsubscribe page their entry in the “Email Campaign – Double Opt In” is removed and then a form displayed “Email Campaign – Unsubscribe” asking for some feedback which is optional.
Notes on email delivery.
I personally use Mailgun https://www.mailgun.com/ and their respective plugin to ensure mail delivery for WordPress, nothing worse than not getting that initial email invite.
Additional information
The shortcode [send_campaign_join_email]
can be used on checkout for example as it will silently run the code and only process the request if the normal conditions are met to send the confirmation email. For example do_shortcode( '[send_campaign_join_email email_address="' . $subscribeEmail . '"]');
Leave a Reply
Want to join the discussion?Feel free to contribute!