Last active
October 9, 2018 10:23
-
-
Save andrejcremoznik/11c3ab2541d207106317209a7644c632 to your computer and use it in GitHub Desktop.
Create a MailChimp subscribe form in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
NOTE: | |
- this is minimal markup | |
- you can add elements and classes however you want | |
- if you change existing classes, match them in the config in the javascript | |
--> | |
<form class="mailchimp"><!-- NOTE: error, success and loading classes will be added here --> | |
<input class="mailchimp__input" type="email" placeholder="Your e-mail" required> | |
<button class="mailchimp__btn" type="submit">Subscribe</button> | |
<div class="mailchimp__feedback"></div> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (SMC, $) { | |
'use strict' | |
function MailChimp () { | |
this.config = { | |
errorClass: 'mailchimp_error', | |
successClass: 'mailchimp_success', | |
loadingClass: 'mailchimp_loading', | |
formEl: '.mailchimp', | |
inputEl: '.mailchimp__input', | |
feedbackEl: '.mailchimp__feedback' | |
} | |
} | |
MailChimp.prototype = { | |
init: function () { | |
$(document).on('submit', this.config.formEl, this.subscribe.bind(this)) | |
}, | |
// Handle form submission | |
subscribe: function (e) { | |
e.preventDefault() | |
var $form = $(e.target) | |
$form.addClass(this.config.loadingClass) | |
$.ajax({ | |
method: 'POST', | |
url: SMC.endpoint, | |
data: { | |
action: 'mailchimp_subscribe', | |
nonce: SMC.nonce, | |
email: $form.find(this.config.inputEl).val() | |
} | |
}) | |
.done(function (rsp) { | |
this.feedback(JSON.parse(rsp), $form) | |
}.bind(this)) | |
.fail(function (err) { | |
this.feedback({ message: SMC.error, success: false }, $form) | |
}.bind(this)) | |
}, | |
// Show feedback after submission | |
feedback: function (rsp, $form) { | |
// console.log(rsp) // Uncomment to see MC API responses | |
$form | |
.removeClass(this.config.loadingClass) | |
.addClass(rsp.success ? this.config.successClass : this.config.errorClass) | |
.find(this.config.feedbackEl) | |
.text(rsp.message) | |
if (rsp.success) { | |
$form.find(this.config.inputEl).val('') | |
} | |
$form.find(this.config.inputEl).one('focus', this.reset.bind(this, $form)) | |
}, | |
// Reset form state | |
reset: function ($form) { | |
$form | |
.removeClass(this.config.errorClass + ' ' + this.config.successClass) | |
.find(this.config.feedbackEl).text('') | |
} | |
} | |
// Run on DOM ready | |
$(function () { | |
var mc = new MailChimp() | |
mc.init() | |
}) | |
})(window.SMC, jQuery) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SimpleMailChimp English template | |
msgid "" | |
msgstr "" | |
"MIME-Version: 1.0\n" | |
"Content-Type: text/plain; charset=utf-8\n" | |
"Content-Transfer-Encoding: 8bit\n" | |
"Language: en_US\n" | |
# http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html | |
"Plural-Forms: nplurals=2; plural=(n != 1);\n" | |
msgid "Something broke. Refresh the page and try again." | |
msgstr "" | |
msgid "Invalid e-mail address." | |
msgstr "" | |
msgid "Thank you! You will shortly receive an email to confirm your subscription." | |
msgstr "" | |
msgid "You are already on our list. If you’ve unsubscribed in the past but would like to rejoin, please contact us." | |
msgstr "" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: SimpleMailChimp | |
* Description: Simple MailChimp for WP | |
* Version: 1.0.0 | |
* Author: Andrej Cremoznik | |
* Author URI: https://keybase.io/andrejcremoznik | |
* Text Domain: smc | |
* Domain Path: /languages | |
*/ | |
if (!defined('WPINC')) die(); | |
use \DrewM\MailChimp\MailChimp; | |
class SimpleMailChimp { | |
private $version = '1.0.0'; | |
public function run() { | |
// Actions | |
add_action('init', [$this, 'plugin_textdomain'], 0); | |
add_action('wp_ajax_mailchimp_subscribe', [$this, 'mailchimp_subscribe']); | |
add_action('wp_ajax_nopriv_mailchimp_subscribe', [$this, 'mailchimp_subscribe']); | |
add_action('init', [$this, 'mailchimp_script']); | |
} | |
// Set plugin textdomain for localization | |
public function plugin_textdomain() { | |
load_plugin_textdomain( | |
'smc', | |
false, | |
dirname(plugin_basename(__FILE__)) . '/languages' | |
); | |
} | |
// Helper function to return an array as json and exit | |
private function ajax_respond($payload, $code = 200) { | |
http_response_code($code); | |
header('Content-Type: application/json'); | |
echo json_encode($payload); | |
die(); | |
} | |
// Load frontend JS to handle form submission | |
public function mailchimp_script() { | |
wp_register_script( | |
'mailchimp', | |
plugins_url('mailchimp.js', __FILE__), | |
['jquery-core'], // Depend on jQuery (core skips the migrate script) | |
$this->version, | |
true | |
); | |
// Inject some dynamic data into the page for the script | |
wp_localize_script('mailchimp', 'SMC', [ | |
'endpoint' => admin_url('admin-ajax.php'), | |
'nonce' => wp_create_nonce('mailchimp'), | |
'error' => __('Something broke. Refresh the page and try again.', 'smc') // Generic error message when the endpoint desn't return HTTP 200 code | |
]); | |
// Load only on frontend | |
if (!is_admin()) { | |
wp_enqueue_script('mailchimp'); | |
} | |
} | |
// Handle the data submitted by frontend | |
public function mailchimp_subscribe() { | |
// Validate nonce - auto-dies if invalid (returns HTTP code 4xx) | |
check_ajax_referer('mailchimp', 'nonce'); | |
// Sanitize entered email - invalid email will not pass and return '' | |
$input_email = sanitize_email($_POST['email']); | |
// Fail if invalid email | |
if (!$input_email) { | |
$this->ajax_respond([ | |
'message' => __('Invalid e-mail address.', 'smc'), | |
'success' => false | |
]); | |
} | |
// Call MailChimp with valid data | |
$mc = new MailChimp(MAILCHIMP_API_KEY); | |
$request = $mc->post('lists/'. MAILCHIMP_SUBSCRIBE_LIST .'/members', [ | |
'email_address' => $input_email, | |
'status' => 'pending' // pending = double opt-in | |
]); | |
// Success/error check | |
if ($mc->success()) { | |
$this->ajax_respond([ | |
'message' => __('Thank you! You will shortly receive an email to confirm your subscription.', 'smc'), | |
'success' => true, | |
// '_debug' => $request | |
]); | |
} else { | |
// MC API errored | |
$rsp = json_decode($mc->getLastResponse()['body'], true); | |
// Default error message | |
$message = __('Something broke. Refresh the page and try again.', 'smc'); | |
// Special case error messages | |
if (isset($rsp['title'])) { | |
switch ($rsp['title']) { // This switch could be extended | |
case 'Member Exists': | |
$message = __('You are already on our list. If you’ve unsubscribed in the past but would like to rejoin, please contact us.', 'smc'); | |
break; | |
} | |
} | |
// Respond with an error | |
$this->ajax_respond([ | |
'message' => $message, | |
'success' => false, | |
// '_debug' => $rsp | |
]); | |
} | |
} | |
} | |
// Run plugin | |
function run_SimpleMailChimp() { | |
$plugin = new SimpleMailChimp(); | |
$plugin->run(); | |
} | |
if (defined('MAILCHIMP_API_KEY') && defined('MAILCHIMP_SUBSCRIBE_LIST')) { | |
if (!empty('MAILCHIMP_API_KEY') && !empty('MAILCHIMP_SUBSCRIBE_LIST')) { | |
run_SimpleMailChimp(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// stuff.. | |
// MailChimp API | |
define('MAILCHIMP_API_KEY', 'API key'); | |
define('MAILCHIMP_SUBSCRIBE_LIST', 'List ID'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment