Last active
February 11, 2023 17:44
-
-
Save caiotarifa/2c58a090c516961dda75 to your computer and use it in GitHub Desktop.
CONTACT FORM 7 -> MAILCHIMP 3.0
This file contains hidden or 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 | |
// -------------------------------------------------------------------------- // | |
// CONTACT FORM 7 -> MAILCHIMP // | |
// -------------------------------------------------------------------------- // | |
// © 2015 Caio Tarifa. All Rights Reserved. // | |
// -------------------------------------------------------------------------- // | |
function wpcf7_send_to_mailchimp() { | |
// Contact Form 7: Variables. | |
$submission = WPCF7_Submission::get_instance(); | |
$data = $submission->get_posted_data(); | |
// Is user allowed? | |
if (!$data['newsletter-opt-in'][0]) { return false; } | |
// MailChimp: Variables. | |
$api_key = ''; | |
$list_id = ''; | |
// MailChimp "Merge Fields" => Contact Form 7 fields. | |
$merge_fields = array( | |
'FNAME' => $data['your-name'], | |
'LNAME' => $data['your-last-name'] | |
); | |
$interests = array( | |
'group-name' => filter_var($data['group-name'][0], FILTER_VALIDATE_BOOLEAN) | |
); | |
// Others... | |
$email = $data['your-email']; | |
// The magic! | |
$domain = explode('-', $api_key)[1]; | |
$domain = 'https://'.$domain.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members'; | |
$request_parameters = json_encode(array( | |
'email_address' => $email, | |
'email_type' => 'html', | |
'status' => 'subscribed', | |
'merge_fields' => $merge_fields, | |
'interests' => $interests, | |
'language' => 'pt' | |
)); | |
$session = curl_init($domain); | |
curl_setopt($session, CURLOPT_HTTPHEADER, array( | |
'Content-Type: application/json', | |
'Authorization: apikey '.$api_key | |
)); | |
curl_setopt($session, CURLOPT_POST, true); | |
curl_setopt($session, CURLOPT_USERAGENT, 'ContactForm7'); | |
curl_setopt($session, CURLOPT_TIMEOUT, 5); | |
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($session, CURLOPT_POSTFIELDS, $request_parameters); | |
$result = curl_exec($session); | |
curl_close($session); | |
return true; | |
} | |
add_action('wpcf7_mail_sent', 'wpcf7_send_to_mailchimp', 1); | |
?> |
@leandroprz I no longer work with WordPress so it's likely that the code is out of date. Are you getting any errors?
There are no error messages. I integrated this into a contact form with a "click to subscribe to my newsletter" checkbox. When sending the message it sends fine, but the email address is not being subscribed to the Mailchimp list.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@leandroprz I no longer work with WordPress so it's likely that the code is out of date. Are you getting any errors?