Your Web News in One Place
September 11, 2019 10:27 am

How to Create a Mailchimp Subscribe Form Widget for WordPress

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

Wewill add our widget as a simple plugin called mailchimp-widget. I won’tdescribe 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 afolder called mailchimp-widget and inside that folder create a mailchimp-widget.phpfile. 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 aMailchimp account, you’ll need to create a mailing list (nowadays referred to as an “audience”) and the API key. 

Mailchimp provides full and detailed informationabout 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 youcan 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 youruser 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 theresults 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 shouldbe 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.

Insidethat 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. Addthe following code after it:

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

Whoa, Slow Down There Cowboy

Fair enough, letme explain what is going on here! 

  • As with any REST API connection we will needto specify the content type we expect to get and make a simple authorizationusing our API key. That is all dealt with in the $headers variable. 
  • Next we set the URL option. 
  • CURLOPT_RETURNTRANSFERis where we tell the curl not to echo the result, but instead write it into variable. 
  • Afterthat we set the request type; the Mailchimp API supportsPOST, 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 falseto certificate verification for TLS/SSL connection. 

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

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

Construct the Endpoint URL

Next up, let’s create the Mailchimp urlwith 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 theresults from transient. This way we can save resources with caching. Ifthere are no results we will show an error message. If any API key is providedI always use it as a part of the transient name, as a way of ensuring unique naming.

Fetch Mailchimp Lists

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

Here we send a request to Mailchimp using our previously createdfunction mailchimp_connect() to get all the lists available. And as the result isrequired 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 validdata and we have at least one Mailchimp list we add the Mailchimp list id andname to our mailchimp_list array. Lastly, if there is valid data, but no list, wedisplay the second error message.

Nowwe 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.

Hereis 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 publicfunction form.

Public Function Form

Here, using our previously created function mailchimp_list(), wefetch 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 tosubscribe.

PublicFunction 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 handlesthe AJAX request and the CSS file adds basic styling.

After that we create the Mailchimp subscribe form structure itself. Here we havethree 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 fromthe user. 

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

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

Now if you go to Admin > Appearance > Widgets you will seeour 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 theprocess 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 emailvalidation 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 ourhidden fields.
  3. Next, before the submission, we need to make sure the emailis 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 actionhandler 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 formfields for future entry.

Now if you go to the front-end and submit the form youwill get the success message, but the subscription won’t actually take place as thesubscribe 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 iset_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. Soif 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 thenonce field is valid and verified; only after that we will subscribe theuser to the list. This is for security reasons., and you can read more aboutnonce in the WordPress codex.

After the nonce verification we can subscribe the userwith a new function that we will build now: mailchimp_post(). It requires severalparameters:

  • 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 followingcode:

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 RESTAPI 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. Soopen 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 subscriptionshould 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


Original Link: https://webdesign.tutsplus.com/tutorials/how-to-create-a-mailchimp-subscribe-form-widget-for-wordpress--cms-33740

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code