iDevie
October 2019
M T W T F S S
« Sep    
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories


In this tutorial I’ll explain how to create a “Mailchimp subscribe form widget” using WordPress, the Mailchimp API, and AJAX. It will be aimed at competent beginner developers, and requires some understanding of PHP and WordPress development. There’s a lot to do, so let’s get stuck in!

A Quick Note on APIs

“The web has gotten really “API-ish”. By that I mean, almost every major site is pushing and pulling content to and from other sites.” – Scott Fennell

I’ve covered APIs a couple of times in recent tutorials, so for a quick definition and to help you get up and running with REST APIs I recommend you take a look at these two resources:

As far as Mailchimp’s API and REST goes, from the documentation:

“Most APIs are not fully RESTful, including the Mailchimp API. But Mailchimp follows most of the practices and common definitions of the style. For example, the Mailchimp API has what we call “resources,” which are typically nouns like “subscribers” or “campaigns.” You take action on resources using the standard HTTP methods: POST, GET, PATCH, and DELETE.” 

Beginning the Mailchimp Subscribe Form Plugin

We
will add our widget as a simple plugin called mailchimp-widget. I won’t
describe in detail how to create a plugin, but I’ll provide some resources below to help you get started if you need them. Begin by creating a
folder called mailchimp-widget and inside that folder create a mailchimp-widget.php
file. Add the following File Header code snippet to the top of the file:

A REST API, as with any API, works with an API key. So at this point you’ll need a
Mailchimp account, you’ll need to create a mailing list (nowadays referred to as an “audience”) and the API key. 

Mailchimp provides full and detailed information
about how to generate your own API key.
And as with any API, Mailchimp have also published very thorough documentation that we can refer to.

So here is our plan:

  1. First we will fetch your Mailchimp lists, so you
    can choose from the widget settings the list to which your users will be subscribed.
  2. Next we will build the widget itself.
  3. Then we will create the action that takes your
    user data from the Mailchimp subscribe form and sends it to Mailchimp using AJAX and the REST API.

Fetch the Mailchimp Lists

Let’s create a simple function that connects to the Mailchimp API using cURL, then caches the
results in a WordPress “Transient” (a way to cache information).

At the top of your plugin add the Mailchimp REST API key as a constant:

Next,
let’s create the Mailchimp connect function. The naming is optional, but should
be descriptive.

This function requires several parameters:

  • $url – the Mailchimp REST API endpoint
  • $api_key – our API key
  • $data – the data we have to transfer to Mailchimp.

Inside
that function add the following code:

As this function will be used to get results from Mailchimp,
we need to build a query from our data and make it part of the url.

With that done we are ready to initialize a cURL connection. Add
the following code after it:

And now using the curl_setopt() function
we can pass the parameters to the curl_init we created earlier.

Whoa, Slow Down There Cowboy

Fair enough, let
me explain what is going on here! 

  • As with any REST API connection we will need
    to specify the content type we expect to get and make a simple authorization
    using our API key. That is all dealt with in the $headers variable. 
  • Next we set the URL option. 
  • CURLOPT_RETURNTRANSFER
    is where we tell the curl not to echo the result, but instead write it into variable. 
  • After
    that we set the request type; the Mailchimp API supports
    POST, GET, PATCH, PUT, and DELETE
  • Next we specify the timeout in seconds. 

Then the final two options you can ignore; we use them to specify the user agent and set false
to certificate verification for TLS/SSL connection. 

Now we can execute the
curl and return the results. The full function looks like this:

If no API key is provided you will see an error
message where you would otherwise expect to see the subscribe list select. 

Construct the Endpoint URL

Next up, let’s create the Mailchimp url
with the api endpoint:

Information on API endpoints can be found in the official Mailchimp documentation.



We now need to check if a transient already exists;
if not we should make a new Mailchimp list fetch, otherwise we will return the
results from transient. This way we can save resources with caching. If
there are no results we will show an error message. If any API key is provided
I always use it as a part of the transient name, as a way of ensuring unique naming.

Fetch Mailchimp Lists

So
now let’s fetch the Mailchimp list. Add the following code:

Here we send a request to Mailchimp using our previously created
function mailchimp_connect() to get all the lists available. And as the result is
required in JSON format we’ll need to decode it.



First let’s make sure that we have the results,
otherwise we’ll display the error message:

After the error check, if we do have valid
data and we have at least one Mailchimp list we add the Mailchimp list id and
name to our mailchimp_list array. Lastly, if there is valid data, but no list, we
display the second error message.

Now
we need to encode, serialize and set the transient:

So the full function looks like this:

Build the WordPress Widget

As with plugin development basics, I won’t cover basic widget creation here, but ours will be a relatively simple widget and I will highlight the most important parts of it.

Here
is the full widget code, paste it inside your plugin’s main file at the end. The most important parts are the public function widget, and public
function form.

Public Function Form

Here, using our previously created function mailchimp_list(), we
fetch the subscription lists from your account and create a select with the data,
so when adding the widget you can choose the list to which you want your users to
subscribe.





Public
Function Widget

Before anything else we enqueue the script and style files for the widget,
so go to the top of your plugin and add the code, right after the Mailchimp API constant.

Be sure to create the js and css folders referenced here, and create the corresponding widget-mailchimp.js/css files inside those folders. The JS file handles
the AJAX request and the CSS file adds basic styling.

After that we create the Mailchimp subscribe form structure itself. Here we have
three fields visible to the user: 

  1. the fname: First name
  2. lname: Last name
  3. and email. 

Hidden Fields

Pay close attention to this code:

This is a very important part of the form; three crucial fields hidden from
the user. 

  1. The first one is the list that the user
    will be subscribed to.
  2. The second one is the action that is required to handle
    the Mailchimp subscription functionality from the AJAX request. You can give any
    value to it, but remember it as we will need it in future. 
  3. And the last one is
    the nonce field that is used for validation. In other words this field value
    should be validated to make sure the request comes from our site.

And also take a closer look at the action and method
attributes of the form:

Now if you go to Admin > Appearance > Widgets you will see
our newly added widget. Add it to the widget area and you will see the subscribe form appear on the front-end!

Our newsletter subscribe form widget

Looking good! If you try to subscribe now nothing will happen as we haven’t yet created the AJAX and action handler yet. Let’s do that next.

Create AJAX POST and Action Handler

Open the JavaScript file we created earlier and paste the following (large amount of) code into it:

This is an AJAX POST that sends our form data to the Mailchimp subscription action handler that we will write in a moment. I broke the
process into seven steps which you’ll see annotated in the snippet. 

At the top of the file, up to line 29, you’ll find an email
validation function. Let me explain each of the other steps here:

  1. First we will need to prevent default submit behavior of the form so that it remains on the page and handles the request with AJAX.
  2. Next we serialize the input data both from the user and from our
    hidden fields.
  3. Next, before the submission, we need to make sure the email
    is valid.
  4. After that we make a simple AJAX POST. Here we need three parameters, the request type: POST, the url – the form action attribute, and the data that is our serialized data.
  5. And if the request is successful we send the data to our action
    handler and show a success message to the user.
  6. If there was an error, we should inform the user.
  7. And always after a success or fail we clean the form
    fields for future entry.

Now if you go to the front-end and submit the form you
will get the success message, but the subscription won’t actually take place as the
subscribe action is not yet created. 

Create the Subscribe Action

And so, for the last part. Go to the plugin’s main file and at the very bottom add the code:

Important!

Notice the last two lines, which are as follows:

The last part of the first parameters of our two actions is
et_mailchimp –this is the hidden field value that we have in our form. By using these, WordPress understands that it needs to handle the specific form request. So
if you used different naming for your hidden action field, make sure your actions are added correctly, like this:

Nonce

You’ll notice the first thing we did was to make sure the
nonce field is valid and verified; only after that we will subscribe the
user to the list. This is for security reasons., and you can read more about
nonce in the WordPress codex.

After the nonce verification we can subscribe the user
with a new function that we will build now: mailchimp_post(). It requires several
parameters:

  • User email
  • Subscriber status
  • Targeted list
  • API key
  • And user data, i.e. first name and last name.

Just before the mailchimp_action() function add the following
code:

It’s very similar to the mailchimp_connect() function we wrote earlier, except it has a different request type, different url.

This function takes our user data and using the Mailchimp REST
API it adds the user to the targeted list using the curl function.

Add Some Simple Styles

Now our widget is complete! We just need to add some subtle style changes. So
open the style file we created earlier and paste the following style rules:

Now, clear the browser cache and visit your site’s front-end to check everything is working perfectly. The subscription
should work on live sties and locally running sites!

Conclusion

I hope you enjoyed this tutorial on creating a Mailchimp subscribe form widget for WordPress, using the Mailchimp API. It was quite a substantial one! Here is the link to the GitHub repo;
you can download the plugin, modify it, and use it in any project you like!

Oo-oo-ooh! More Mailchimp Goodness


Comments 0
There are currently no comments.