How to Create a MailChimp Opt-In Checkbox for Contact Form 7 WITHOUT a WordPress Plugin
In today’s post, we’re going to head a slightly different direction in our coding series and move away from WooCommerce for a bit to look at another problem that’s not well explained on the Internet—how do you set up/integrate/configure MailChimp opt-in with Contact Form 7 (CF7) in WordPress without using a plugin?
This is an interesting question that we recently had to solve for a project, and there’s no real guide out there on the web that explains what to do. Sure, there are a bunch of Stack Overflow posts, and some other outdated blog posts, but nothing really current for this year (a lot of API hooks and calls have changed since then).
Why Not Just Use a Plugin?
This is a really good question, and it’s something that we wanted to take a moment to address…
There are some great plugins out there for MailChimp and Contact Form 7, but we’re big fans of keeping plugins to a minimum for a variety of reasons, such as:
- Plugins can slow down a WordPress site
- Plugins can cause conflicts and incompatibilities
- Plugins can create security vulnerabilities
- Plugins may leak or expose data or activity
- Plugins may not have the same functionality as custom code
While there are other reasons to write your own code (which includes the benefits of learning how to code) vs. a plugin, we typically opt for a code solution over a plugin when possible.
There are some situations though (especially with officially supported plugins) where it is much easier and more efficient to use a plugin. However, in this case, it seemed like custom code was a great option.
So, let’s take a look at the problem, and how we solved it!
The MailChimp API, WordPress Functions, & More
In order to connect MailChimp to your WordPress installation, you’ll need to use their API, which is a feature that allows your website to interact which their software. With the API, you can push data to your MailChimp lists directly from your contact forms.
However, it’s not that simple—you have to collect the data from Contact Form 7, process it, and then push it to MailChimp using the correct parameters. If something is wrong, incorrect, or not coded properly, the data will not push to MailChimp properly.
There may also be other parameters that you need to address, depending upon what you’re looking to do.
Things You’ll Need to Start – A MailChimp API, Your List ID, and DrewM’s PHP Wrapper
1) Let’s start with MailChimp—you’ll need to login and grab your API key ahead of time. This is the secure key what will allow your website to interface with MailChimp’s servers. You can find it in the Account > Extras section of your MailChimp account:
2) Once you have your API key, you’ll need to grab the list ID (also known as the audience ID) for the specific MailChimp list that you want to push your form data to. This information will be in the Lists > Settings > Audience name and defaults section of your MailChimp account. You can find that here:
3) Head over to Github and download Drew M’s PHP API wrapper. You can find that here:
https://github.com/drewm/mailchimp-api
Download the entire zip folder, unzip it, navigate to the /src/ folder and save the MailChimp.php file—this is all you’ll need for WordPress. Upload this file to your server via FTP and save the file path, because you’ll need this later.
Putting It All Together – The Custom MailChimp/WordPress/API Script
In order to make all of these things work, we wrote some custom code to create a function that’s added to WordPress via your functions.php file. We’ll post the code below, and then break down what each section does, and why you need it. So, here’s the full script (that you’ll paste at the end of your functions.php file, after editing the places where you need to put your specific pieces of information):
// Function to add an opt-in checkbox for MailChimp to WordPress Contact Form 7 Without a Plugin function chimp_subscribe( $contact_form ) { $submission = WPCF7_Submission::get_instance(); // Get the CF7 instance and assign it to a variable if ($submission && $contact_form->id() == 'YOUR FORM ID GOES HERE') { // Restrict this function to a single form $data = $submission->get_posted_data(); // Get the form data // Handle the form data $email = $data['your-email']; $phone = $data['your-tel']; // BEGIN manipulating names $names = $data['your-name']; // Pull CF7 names here $names_one_space = preg_replace('/\s\s+/', ' ', $names); $names_arr = explode(' ', $names_one_space); $firstName = $names_arr[0]; if (count($names_arr) > 1){ // If user inputs more than just a first name // maniuplate last name $lastName = array_slice($names_arr, 1); $lastName2 = implode(" ", $lastName); } else { $lastName2 = " "; // If the user only types a first name, leave the last name box blank } //END manipulating names $mergeVars = array( // Create the array to send the data to the MailChimp API 'FNAME'=>$firstName, 'LNAME'=>$lastName2, 'PHONE'=>$phone ); $checkbox = $data['mailchimp-checker'][0]; // Get the checkbox state - is it checked or unchecked? if ($checkbox != ""){ //if checkbox is checked include( get_stylesheet_directory() .'/YOUR FILE PATH GOES HERE/MailChimp.php'); // This is the file path where you uploaded this file from Github. $MailChimp = new \DrewM\MailChimp\MailChimp('YOUR MAILCHIMP API KEY GOES HERE'); // Instantiate new object with MailChimp API key $list_id = 'LIST ID GOES HERE'; // Your list ID // Send data to MailChimp using Drew PHP API wrapper $result = $MailChimp->post("lists/$list_id/members", [ 'email_address' => $email, 'status' => 'subscribed', 'merge_fields' => $mergeVars, ]); } return $contact_form; // Return form data to function } } add_action( 'wpcf7_mail_sent', 'chimp_subscribe' ); // Add function to functions.php and call it after the form is submitted
Individual Code Parts Broken Down Step-By-Step
So, like we always do to make it easier to understand, we’ll break the code down step-by-step. Here’s the first part:
// Function to add an opt-in checkbox for MailChimp to WordPress Contact Form 7 Without a Plugin function chimp_subscribe( $contact_form ) { $submission = WPCF7_Submission::get_instance(); // Get the CF7 instance and assign it to a variable if ($submission && $contact_form->id() == 'YOUR FORM ID GOES HERE') { // Restrict this function to a single form
In this section, we’re doing a few things. First, we start the function, and then we get the instance of CF7 and assign that to a variable ($submission) so we can use it.
Then, we have some conditional logic that checks two things: 1) if the form was submitted, and 2) for a specific form ID.
The form ID part is important because you may have multiple forms on your site, and all of them don’t necessarily have an opt-in, and you won’t want to run this function in places you don’t need it. You can get the Form ID of the form you are targeting from the Contact > Contact Form menu on WordPress. It should look like this, where the ID of this example form is “4” as shown below:
Next, we’re going to get the posted data from the form in this section of code:
$data = $submission->get_posted_data(); // Get the form data // Handle the form data $email = $data['your-email']; $phone = $data['your-tel'];
This may differ slightly depending upon the specific fields you have on your form, but make sure that you call them by the form names set in the shortcodes (your-email, your-tel, etc.). We’ll cover how to implement those at the end of the post and how to set up your form for compatibility.
Now, on the form we were working on, there was a singular name field (not first and last name), so we wanted a way to split the first/last names into the first and last name field on MailChimp, like this:
The following code parses, trims, and populates the name field to segment these names. It also accounts for someone typing a two-word last name and a lot of other errors:
// BEGIN manipulating names $names = $data['your-name']; // Pull CF7 names here $names_one_space = preg_replace('/\s\s+/', ' ', $names); $names_arr = explode(' ', $names_one_space); $firstName = $names_arr[0]; if (count($names_arr) > 1){ // If user inputs more than just a first name // maniuplate last name $lastName = array_slice($names_arr, 1); $lastName2 = implode(" ", $lastName); } else { $lastName2 = " "; // If the user only types a first name, leave the last name box blank } //END manipulating names
After we’ve successfully parsed the name fields, we need to work on a few other things. In the following code, we’ll set up an array to send the information we’ve collected to MailChimp’s API, and then we’ll test whether the checkbox has been checked—here’s the code for that:
$mergeVars = array( // Create the array to send the data to the MailChimp API 'FNAME'=>$firstName, 'LNAME'=>$lastName2, 'PHONE'=>$phone ); $checkbox = $data['mailchimp-checker'][0]; // Get the checkbox state - is it checked or unchecked? if ($checkbox != ""){ //if checkbox is checked
If the checkbox is checked, we’ll use Drew M’s API wrapper to send the information to our MailChimp account via the API and add this person as a subscriber:
include( get_stylesheet_directory() .'/YOUR FILE PATH GOES HERE/MailChimp.php'); // This is the file path where you uploaded this file from Github. $MailChimp = new \DrewM\MailChimp\MailChimp('YOUR MAILCHIMP API KEY GOES HERE'); // Instantiate new object with MailChimp API key $list_id = 'LIST ID GOES HERE'; // Your list ID // Send data to MailChimp using Drew PHP API wrapper $result = $MailChimp->post("lists/$list_id/members", [ 'email_address' => $email, 'status' => 'subscribed', 'merge_fields' => $mergeVars, ]); } return $contact_form; // Return form data to function
As mentioned above, there are some things that you’ll need to replace with your information where noted (API key, list ID, form ID, file path to MailChimp.php).
add_action( 'wpcf7_mail_sent', 'chimp_subscribe' ); // Add function to functions.php and call it after the form is submitted
Calling This Function Via Contact Form 7
Now, in order to call this function on your form and make sure it works, you’ll need to make sure that the ID names in the shortcodes is the same as the ID names on this form. That would look something like this:
[text 1="your-name" language="*"] [email* your-email] [tel your-tel] [checkbox mailchimp-checker]
These are the Contact Form 7 shortcodes that generate the fields. They need to retain these names in order to work with the code, as mentioned above. You can choose to add other parameters to these shortcodes, or you may have other fields that you need to include, which you can modify to fit your needs.
And that wraps up another installing in the Web Hosting Buddy WordPress coding series! We wanted to take the time to create this because there weren’t any working solutions we could find anywhere online.
The nice thing about writing your own code is that you can customize it to parse names and do other things that plugins can’t. Feel free to use, reuse, and modify this code—we hope this helps you get up and running with MailChimp and Contact Form 7 without the need for a plugin!