top of page

Connect Mail chimp With Contact Form 7 with API and Without any other Plugin

  • Writer: سُلَيْمَان بْن دَاوُوْد
    سُلَيْمَان بْن دَاوُوْد
  • May 30, 2020
  • 1 min read

Mail chimp is a very popular marketing email blast platform consisting of Audience(List Previously) and we can connect our contact form 7 with ease

Here is the code that needs to be placed on functions.php On below code the 17 is the contact form 7 id in the back end


Further the API Key and List ID needs to be pulled form Mailchimp Account on below example we also merged couple of form fields to be sent over mailchimp



 add_action("wpcf7_before_send_mail", "wpcf7_do_something_else",90,1);  
function wpcf7_do_something_else($cf7) {
    $wpcf = WPCF7_ContactForm::get_current();
    $submission = WPCF7_Submission::get_instance();
    $posted_data = $submission->get_posted_data(); 
     if($posted_data['_wpcf7'] == 17){
            $apiKey      = get_field('mailchimp_api_key','option');
            $listId      = get_field('audience_id','option');
            $memberId    = md5(strtolower(  $posted_data['your-email'] ));
            $dataCenter  = substr($apiKey,strpos($apiKey,'-')+1);
            $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
            $json = json_encode([
            'email_address' => $posted_data['your-email'],
            'status' => 'subscribed',
            'merge_fields' => [
            'FNAME' => $posted_data['first-name'],
            'LNAME' => $posted_data['last-name'],
            'INTERESTED' => $posted_data['interested-in'],
            'MESSAGE' => $posted_data['your-message'],
            ]
            ]);
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
     }
    return $cf7;
}





Recent Posts

See All
Hide Upcoming Events

Hiding Upcoming Events can be relatively useful when you are using ACF fields to show Dates for an an Event The Following Snippet is an...

 
 
 

Comments


© 2020 by syednazrulhassan

bottom of page