Created
September 11, 2015 12:27
-
-
Save AminulBD/3acce80dfc0d481522e8 to your computer and use it in GitHub Desktop.
Mailchimp Subscribe for wordpress ajax.
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
/** | |
* Mailchimp Email Subscription Handler | |
* | |
* @since 1.0.0 | |
* @version 1.0.0 | |
* @author Aminul Islam <aminmedia@gmail.com> | |
*/ | |
function yourtheme_mailchimp_subscribe() { | |
// MC API and List ID | |
$mc_api = 'API Key"; | |
$mc_list = 'List ID'; | |
// Get the Server ID | |
$srv = substr($mc_api, -3); | |
$subscribe_url = 'https://' . $srv . '.api.mailchimp.com/2.0/lists/subscribe'; | |
// Prepare email for MC | |
$user_email = new StdClass(); | |
$user_email->email = $_REQUEST['email']; | |
// Prepare name for MC | |
$user_info = new StdClass(); | |
$user_info->fname = (!empty($_REQUEST['fname'])) ? $_REQUEST['fname'] : '' ; | |
$user_info->lname = (!empty($_REQUEST['lname'])) ? $_REQUEST['lname'] : '' ; | |
$parameters = array( | |
'apikey' => $mc_api, | |
'id' => $mc_list, | |
'email' => $user_email, | |
'merge_vars' => $user_info, | |
'double_optin' => false, | |
'send_welcome' => true | |
); | |
// Get data from MC | |
$mc_return_data = wp_remote_post( $subscribe_url, array( | |
'body' => json_encode($parameters), | |
'headers' => array('Content-Type: application/json') | |
)); | |
// Decode JSON Data | |
$mc_request = json_decode($mc_return_data['body'], true); | |
if ( !empty( $mc_request['code'] ) && $mc_request['code'] === -100) { | |
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { | |
echo 'Invalid Email Address'; | |
die(); | |
} else { | |
wp_redirect( home_url() ); | |
exit(); | |
} | |
} else if ( !empty( $mc_request['code'] ) && $mc_request['code'] === 214 ) { | |
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { | |
echo "You are already on the list"; | |
die(); | |
} else { | |
wp_redirect( home_url() ); | |
exit(); | |
} | |
} else { | |
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { | |
echo "You are added to your newsletter subscriber list."; | |
die(); | |
} else { | |
wp_redirect( home_url() ); | |
exit(); | |
} | |
} | |
} | |
// Action it for ajax request | |
add_action( 'wp_ajax_nopriv_yourtheme_mailchimp_subscribe', 'yourtheme_mailchimp_subscribe' ); | |
add_action( 'wp_ajax_yourtheme_mailchimp_subscribe', 'yourtheme_mailchimp_subscribe' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment