Make a MailChimp subscribe form by hand

I used to just take the MailChimp for WP plugin until it stopped working – at least the front-end facing JavaScript part of it did. Looking at the code that handles form submission on front-end gave me a headache so I decided it was time I wrote it myself and stop worrying about theme integration and localization for the rest of my life.

Let’s code

1. Dependencies

You will need the MailChimp API by Drew McLellan. If you’re managing your project with composer (which you should) it’s as simple as running:

composer require drewm/mailchimp-api

2. Configuration

Be careful not to commit your MailChimp API credentials to your code repository. Credentials belong into a database or an environment configuration file. Since I want to keep the code here minimal, lets define 2 globals.

If you use dotenv or some kind of environment configuration, you’ll know where to put these, if not, wp-config.php will work.

https://gist.github.com/andrejcremoznik/11c3ab2541d207106317209a7644c632#file-wp-config.php

3. Ajax endpoint for MailChimp subscription

The code below is a fully functional plugin. While it can be used as is, you should ideally integrate it into your own codebase.

Place the following into wp-content/plugins/smc/smc.php:

https://gist.github.com/andrejcremoznik/11c3ab2541d207106317209a7644c632#file-smc.php

4. Front-end form submission

The JavaScript referenced from the PHP plugin above. The script will work for any number of forms on the page as long as they share the same class names.

Place the following into wp-content/plugins/smc/mailchimp.js:

https://gist.github.com/andrejcremoznik/11c3ab2541d207106317209a7644c632#file-mailchimp.js

5. The HTML markup

Use the following markup as many times as you want on a page. You can add wrappers, move stuff around, add classes, basically make it fit your theme. If you change the default classes, make sure to update the config in the above JavaScript file.

https://gist.github.com/andrejcremoznik/11c3ab2541d207106317209a7644c632#file-form.html

6. Internationalization

You can simply translate everything as you would with any another plugin. Create a sub-directory called languages and fill it with localisations. Below is the English template from the above files:

https://gist.github.com/andrejcremoznik/11c3ab2541d207106317209a7644c632#file-smc-en_US.pot

Done

That’s all. A fully functional replica of MailChimp for WP in less than 200 lines of code. Should be tiny and to the point so you can expand on it and adapt it to your needs. Don’t waste time trying to wrap your head around some plugin that needs extra plugins just to get some basic functionality going.