Mailchimp Signup Form for WordPress

If you like to offer a newsletter for your website’s visitors, Mailchimp is one of the first choices because of the great interface they offer. If you like to include the signup form in your WordPress website it’s possible to use their plugin or you can add some HTML code using the default WordPress text widget. In the past we posted an article about how to use the Mailchimp API together with your contact form script. Today we use the same kind of script to integrate the signup form in WordPress. You can check my working Mailchimp signup form on this website (it’s double opt-in signup, if you don’t like to subscribe ingore the mail which is send by Mailchimp).

Why should I use the Mailchimp API for the signup process?

There are different methodes to include the Mailchimp signup form in your WordPress website:

Mailchimp plugin or widget

The Mailchimp widget is very easy to integrate in your sidebar or any other widgetized area and works fine for basic usage. If you need more “freedom” you should know that there are limitations: You can style your form a lot using CSS but you can’t use your own HTML code. The settings page offers a lot features, but the advanced user will always use a feature in a different way. If you don’t like to write code, USE this plugin!

Mailchimp forms for your website

In the Mailchimp section “Lists” is a sub-section that offers 3 different forms for your website. A basic form which is great if you like to use your own design, a classic form which will use the style from your Mailchimp list configuration and the “Super slim form” with cool Ajax effects. You can use them all within WordPress if you include the code right in your WordPress theme.

Using the Mailchimp API

If you like 100% freedom in your design and application you need to use the API system. This way it’s your decission how to integrate the form in your website. In this tutorial I create a WordPress shortcode that will build a form in a page, widget or theme. The used code is able to communicate with the WordPress Ajax API system.

Preparations

Before you follow this tutorial you need a self-hosted WordPress installation, a working Mailchimp account, a working mailing list and also a Mailchimp API key.

Mailchimp merge tags

Mailchimp signup form

I like to use a form right in my post or page using jQuery to process the form request. I create a simple form with 3 fields: First name, last name and the email addres. Place this shortcode in your functions.php file:

function createMCForm() {
	return '
	<div id="formcont">				
		<form id="myform">
			<p>
				<label for="name">First name:</label>
				<input type="text" name="name" id="name" size="30" />
			</p>
			<p>
				<label for="lname">Last name:</label>
				<input type="text" name="lname" id="lname" size="30" />
			</p>
			<p>
				<label for="email">E-mail:</label>
				<input type="text" name="email" id="email" size="30" />
			</p>
			<p>
				<input type="hidden" name="action" value="ajax_action" /> 
				<input type="button" value="Submit" id="submit_button" /> 
			</p>
		</form>
	</div>
	<div id="output"></div>';
}
add_shortcode('MCform', 'createMCForm');

Note the hidden field called “ajax_action”, this is the name of the action which sends the Ajax request to the WordPress Ajax API.

The jQuery code to process the Ajax form request

I used this kind of code for several Ajax contact forms in the past. There is one important point I need to mention, you need to use “jQuery(document)” instead of “$(document)” in your code to get it working in WordPress. How the jQuery Ajax functions works is not part of this tutorial.

jQuery(document).ready(function($) {
	$('#submit_button').click(function() { 
		$.ajax({
			type: 'POST',
			url: ajax_object.ajaxurl, 
			data: $('form#myform').serialize(),
			dataType: 'json',
			beforeSend: function() {
				var name = $('#name').val();
				var lname = $('#lname').val();
				var email = $('#email').val();
 
				if (!name || !email) { 
					$('#output').html(ajax_object.errorEmpty);
					return false; 
				}
				emailpat = /^([a-z0-9])+([\.a-z0-9_-])*@([a-z0-9])+(\.[a-z0-9_-]+)+$/i;
				if (!emailpat.test(email)) {
					$('#output').html(ajax_object.errorEmail); 
					return false;
				}
			},
			success: function(response) {
				if (response.status == 'success') {
					$('#formcont').html('');
 
				}
				$('#output').html(response.errmessage);
			}
		});
	});
});

Using this code snippet I do some basic form validation and the “ajax_object” declarations are used for the error messages. These are the objects I’ve defined inside the functions.php file. After the form is proecessed, we empty the “#formcont” container on success and/or showing an (error) message.

Add this code to a file named “mailchimp.js” and upload the file to the “js” directory inside your theme directory (create the directory if it doesn’t exists). To include the new JavaScript file in your WordPress header you need to add this code BEFORE the code which starts with “wp_localize_script…” to your functions.php file:

wp_enqueue_script( 'ajax-script', plugin_dir_url(__FILE__).'mailchimp.js', array('jquery'), 1.0 ); // jQuery will be included automatically

Using the WordPress Ajax API

Using the function “wp_localize_script()” we’re able to define client side variables inside the WordPress header. We define this way the form’s “action” and two error messages for the form validation process. Add this code to your functions.php file, too.

wp_localize_script( 'ajax-script', 'ajax_object', array( 
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'errorEmpty' => __( 'The first name and the e-mail field are required' ),
				'errorEmail' => __( 'The entered e-mail address is not valid.' )
		) 
);

Register the subscription using the MailChimp API

First I add two actions to the WordPress “system” to include my custom function named “ajax_action_stuff”. Iniside the function you need to add the Mailchimp API key and the ID from the mailing list you have created in Mailchimp. Next I check the submitted form values and than we use cURL to send the values to the Mailchimp system. Your Mailchimp URL might be different from mine, the URL depends on how old your account is. Read this information from the API documentation to learn which URL works with your API key.

 
add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action_stuff' ); // ajax for not logged in users
 
function ajax_action_stuff() {
	$resp['status'] = 'error';
	$resp['errmessage'] = '';
	$apikey = 'your api key';
	$listID = 'your list ID';
	if (!empty($_POST['email']) && !empty($_POST['name'])) {
 
		$name = $_POST['name'];
		$lname = $_POST['lname'];
		$email = $_POST['email'];
 
		$url = sprintf('http://api.mailchimp.com/1.2/?method=listSubscribe&apikey=%s&id=%s&email_address=%s&merge_vars[OPTINIP]=%s&output=json&merge_vars[FNAME]=%s&merge_vars[LNAME]=%s', $apikey, $listID, $email, $_SERVER['REMOTE_ADDR'], $name, $lname);
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$data = curl_exec($ch);
		curl_close($ch);
		$arr = json_decode($data, true);
		if ($arr == 1) {
			$resp['errmessage'] = 'Check now your e-mail and confirm your subsciption.';
			$resp['status'] = 'success';
		} else {
			switch ($arr['code']) {
				case 214:
				$resp['errmessage'] = 'You are already subscribed.';
				break;
				// check the MailChimp API for more options
				default:
				$resp['errmessage'] = 'Unkown error...';
				break;			
			}
		}
	} else {
		$resp['errmessage'] = 'Missing required fields!';
	}
	header( "Content-Type: application/json" );
	echo json_encode($resp);
	exit;
}

After the data was submitted I use the response to decide which information I need to send back to the web client. There are more error codes, but in my opinion the code 214 (already subscribed) is the most common code. Add more cases with different error codes to the switch statement if you like, find more information about Mailchimp error codes here.

What happens next?

The PHP script will create from the “$resp” array a JSON string which is returned to your Ajax script. This script will output a message and will empty the form container on success. Add the shortcode named “MCform” to your post, widget or theme and don’t forget to add some CSS rules to your stylesheet.

Tutorial code download
We put all the code together and created a plugin for some easy implementation. There is no settings screen, that will say you need to add the API key and list ID right into the plugin file. Download the WordPress plugin here.

I hope you like this tutorial and if you have questions or comments you’re welcome to post them below.

Comments

  1. This is timely and appropriate to what I’m working on right now. Thanks very much!

  2. Hi Brandon, great that my tutorial helps :)

  3. Hello Olaf

    I am new to WordPress neither am i a php expert but wanted a Mailchimp subscription form the way you have explained in this tutorial So when i try to insert the code “function createMCForm() { …….” in functions.php file My WP site becomes completely blank showing no admin – dashboard or the site. My theme function file already has a function defined in it that says ”

    Code removed, use pastebin.com instead

    so the moment i add your code in it everything goes blank :(

    Can you pl help/guide where to insert the code in function.php file

    Waiting to hear from you.

    Renu

  4. Hello Renu,

    just follow the tutorial, that your screen becomes blank after adding some code to the functions.php file, is related to PHP syntax errors.
    You can check the server’s error log file for more information.

  5. Yes Olaf you are right the error is a php syntax error mentioned in the error log file. The error is below :
    PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

    Can you help me get rid of this error. The function that’s already in my theme calls for a register sidebar that has few arrays defined for it like name, before widget, after widget, ….

    Renu

  6. Renu,
    post the code via pastebin and share the URL here. The WordPress comment system is doing some filter action on your input (code)

  7. Hello Olaf

    I tried the code and now its not showing any PHP syntax error and the code given by you is placed at a right place in my functions.php. So heading ahead with rest of the tutorial.

    Thanks for letting me know that i can see the php syntax errors in error log file :)

    Renu.

  8. Great let me know if your Mailchimp form is finished :)

  9. Olaf sorry to trouble you again I am done with including the codes to the function.php and a mailchimp.js file inside the js folder. As instructed when i place the shprt code inside the php file i still donot see my form elements though rest of the elemets of that particular page show

    Its a .php file where i am placing the short code i tried placing it just”MCform” as explained by you and also tried “<?php //use shortcode …….." but neither worked :( when i just place the name of the shortcode MCform i see the same text on that page between the container div but not the form :(

    Can you help ?

  10. Post all code from your functions.php file @pastebin.com and I will take a look on the code.

  11. Olaf

    I have placed the code in pastebin now and the title is Mailchimp Form. Kindly check
    The url for the code is http://pastebin.com/h4AaGkv2

    Renu

  12. Renu,
    all your code is inside the forst function at the top, you need to close the curly bracket first and the place the new functions / code.
    After that you should be able to use the shortcode “MCform”

  13. Olaf

    I closed the first function with curly bracket still its now showing the form. Here’s the url with updated curly bracket change: http://pastebin.com/aGEM1H5u

    Renu

  14. The function for creating the shortcode is very basic and I don’t think that there is the problem. How do you use the shortcode?

  15. I placed the shortcode MCform with and without the quotes too but either ways it shows the respective shortcode name only within the container div.

    I also tried to place it using a php function to add shortcode in that case it doesnot show any text within that container div here’s the url for the php function i am using for shortcode : http://pastebin.com/BFvm7DJZ

    Renu

  16. Hello Olaf

    The Mailchimp form is showing on my template now :) I did few changes to my template file and then inserted the shortcode to the html editor through the admin – Pages Finally the form showed but when i try to put a wrong email id or leave it blank too i dont get any error msg nor does the form submit or show a submit response. I checked the source code of my page and i noticed that there’s no maichimp.js file too in the head section. So is it because of this that the form error , response messages are not showing ?

    waiting for reply

    Renu

  17. I will put the files into one download, check back later this weekend. This way I can’t see what is wrong. Maybe it’s your theme, some other plugin or?

  18. Hi Olaf,

    I tried making the code work, following all the instructions you posted but no luck yet. It would be really helpful if you could zip and share the code and I can locate what am i missing.

    Thanks alot !

  19. @Renu, Check the download link for the plugin at the bottom from the article.

  20. Fantastically simple plugin Olaf. Thank you very much – worked perfectly.

    Note that if you’re doing the shortcode outside of a post (e.g. a sidebar) you need to echo the do_shortcode function.

    Good work :)

  21. Olaf, thanks a million for posting this. Nothing else worked for me.

    However I’m curious because as soon as I activate the plugin WordPress throws an error message in debug mode:

    “Notice: wp_enqueue_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or init hooks. Please see Debugging in WordPress for more information. (This message was added in version 3.3.)…”

    This error message does not however keep the plugin from working. I’m just curious because it does seem you’ve enqueued the script correctly. Any clue what this is?

    When I deactivate the plugin, the message goes away, so i’m pretty sure it’s coming from this.

  22. Hi Nimmolo,
    You’re right according the manual you have to call the function a different way like:

    function mailchimpSignup_enqueue_script() {
    	wp_enqueue_script( 'ajax-script', plugin_dir_url(__FILE__).'mailchimp.js', array('jquery'), 1.0 );
    }
     
    add_action( 'wp_enqueue_scripts', 'mailchimpSignup_enqueue_script' );

    The tutorial was written for a previous WordPress version, that’s why you get this warning.

Because of all the spam attemps I've decided to close the comment form at this time. If you have have any questions or comments please post them by using Google+ or Twitter (the links to my profiles are located at the top of this page).