Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Campaign Monitor API add list subscriber via custom form in wordpress theme
<?php
add_action('tb_ajax_newsletter_signup', 'ajax_newsletter_signup');
add_action('tb_nopriv_ajax_newsletter_signup', 'ajax_newsletter_signup');
function ajax_newsletter_signup() {
require_once '../libs/campaignmonitor/csrest_subscribers.php';
$message_success = 'Thanks for signing up';
$message_error_general = 'There was a problem with the newsletter signup submission. Please try again.';
$message_error_email = 'Please enter a valid email address';
$message_error_name = 'Please enter a valid name';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
ajax_return_response(true, $message_error_general);
} else {
$api_key = get_option('options_campaign_monitor_api_key');
$list_id = get_option('options_campaign_monitor_list_id');
$name = array_key_exists('name', $_POST) ? $_POST['name'] : '';
$name = clean_input($name);
$email = array_key_exists('email', $_POST) ? $_POST['email'] : '';
$email = clean_input($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
ajax_return_response(true, $message_error_email);
} else if (empty($name)) {
ajax_return_response(true, $message_error_name);
} else {
try {
$auth = array(
'api_key' => $api_key
);
$wrap = new CS_REST_Subscribers($list_id, $auth);
$result = $wrap->add(array(
'EmailAddress' => $email,
'Name' => $name,
'ConsentToTrack' => 'yes',
'Resubscribe' => true
));
if ($result->was_successful()) {
ajax_return_response(false, $message_success);
} else {
ajax_return_response(true, $message_error_general);
}
} catch (Exception $e) {
ajax_return_response(true, $message_error_general);
}
}
}
}
function ajax_return_response($error, $message) {
header('Content-Type: application/json');
$result = [
'error' => $error,
'message' => $message
];
echo json_encode($result);
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment