» » » Add a MailChimp Signup Form to Your Website

Add a MailChimp Signup Form to Your Website

posted in: WordPress | 0

A few days ago, I got a request to add the signup form from MailChimp to the WordPress site. There are four fields in the form which are first name, last name, phone number, and email. All fields are required. Phone number and email must validate. After submitting the form, we will show the success message on the same page. The submit form will process by Ajax. let’s do this.

 

MailChimp register and login

  • Register and Login

First, we need the MailChimp account. You can register one for free. Go ahead to register your account. Then log in to MailChimp.

  • Create new List

Next, create the new list. At the left top menu, click on Lists menu. Then click on Create List button. You will see a new form, fill in the data you want and hit save button.

  • Create the custom form

Now, create a new signup form. From the new list that you just create, click on Signup forms. The default fields for the signup form are first name, last name, address(hidden field) and email. But we need one more field which is the phone number. So you want to create the custom form. Click on Form Builder option.

Now, you are in Form builder page. At Forms and response emails section, the default choice is Signup form which is the one we need. So leave as it. Here is what you see now.

You can delete the address field which is one of the default fields from MailChimp and it is set as a hidden field. Meaning, at the frontend, users can NOT see this field but the backend you can. Next, you add a new phone number in the form. Then you can reorder the fields in the form you want. Simply drag and drop the fields in a new position in the form. Now, your custom form will look like this.

After that, click on Sign up forms again. This time clicks on Embedded forms option. At the Preview section, you will see the custom form that you just build it. In order to make the form has the same style as your website, we will choose the Naked option. So click on Naked option. Then adjust the form as you need. See the sample below.

Finally, you will get the HTML code for the signup form from MailChimp. Copy the HTML code and paste it somewhere. You will need it when you are working on WordPress.

 

 

Embedded the signup form into WordPress

  • Go to the template you want to add the signup form or create a new template for it.

For example, you can create a newsletter template as template-newsletters.php and add the “template name” in the file like this.

<?php
/*
 * Template Name: Newsletter
 * Author :  Apple Rinquest
 * Theme : ABC
 */
 get_header();
 // your code goes here
 get_footer();
  • Now, paste the HTML code that you copy earlier in this file. The file now looks like this.
<?php
/*
 * Template Name: Newsletter
 * Author :  Apple Rinquest
 * Theme : ABC
 */
 get_header();
 ?>
  <form action="https://redapple.us9.list-manage.com/subscribe/post?u=fab961a518297641fd0e85dbc&id=a84cf79edf" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" target="_blank">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-8 col-md-offset-1 col-sm-7 col-sm-offset-2">
        <h3 class="padding-b-30"><?php echo $lbl_newsletter_title ?></h3>

        <div class="form-group form-inline">
          <div class="row">
            <div class="col-lg-3 col-sm-3">
              <label for="mce-FNAME"><?php echo $lbl_firstname ?> </label>
            </div>
            <div class="col-lg-9 col-sm-9">
              <input type="text" value="" name="FNAME" id="mce-FNAME" class="form-control" placeholder="<?php echo $lbl_firstname ?>" required>
              <div class="help-block with-errors"></div>
            </div>
          </div>
        </div>


        <div class="form-group form-inline">
          <div class="row">
            <div class="col-lg-3 col-sm-3">
              <label for="mce-LNAME"><?php echo $lbl_lastname ?> </label>
            </div>
            <div class="col-lg-9 col-sm-9">
              <input type="text" value="" name="LNAME" id="mce-LNAME" class="form-control" placeholder="<?php echo $lbl_lastname ?>" required>
              <div class="help-block with-errors"></div>
            </div>  
          </div>
        </div>


        <div class="form-group form-inline">
          <div class="row">
            <div class="col-lg-3 col-sm-3">
              <label for="mce-PHONE"><?php echo $lbl_phone ?> </label>
            </div>
            <div class="col-lg-9 col-sm-9">
              <input  type="tel" name="PHONE" value="" id="mce-PHONE" class="form-control" required>
              <div id="error-msg" class="hide" style="color:#dc2531;padding-top:10px;"><?php echo __('Invalid number', 'pih') ?></div>
              <div class="help-block with-errors"></div>
            </div>
          </div>
        </div>


        <div class="form-group form-inline">
          <div class="row">
            <div class="col-lg-3 col-sm-3">
              <label for="mce-EMAIL"><?php echo $lbl_email ?> </label>
            </div>
            <div class="col-lg-9 col-sm-9">
              <input type="email" value="" name="EMAIL" id="mce-EMAIL" class="form-control" placeholder="<?php echo $lbl_email ?>" required>
              <div class="help-block with-errors"></div>
            </div>  
          </div>
        </div>

        <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_a70420c36e13457523701704b_9e50ae4413" tabindex="-1" value=""></div>
        <div class="text-right">
          <input type="submit" value="<?php echo $lbl_submit ?>" name="subscribe" id="mc-embedded-subscribe" class="btn-border btn-transparent btn-margin hover-dark">
        </div>
      </div>

    </div>
  </form>

 <?php get_footer();

You can add more HTML tags or remove the HTML tags you want. Also, you can add or remove the class you want. So the form matches to your website.

 

  • Next, we want to submit the form via ajax and get the status back from MailChimp.

At the form action URL, we will change post?u= to post-json?=u. So we can send the JSON data through our Ajax and get the result back from the request. Also, you should add &c=? at the end of the URL to avoid the cross-domain issue.

From the form above, the form action URL looks like this.

https://redapple.us9.list-manage.com/subscribe/post-json?u=fab961a518297641fd0e85dbc&id=a84cf79edf&c=?

 

  • Now the form is ready to submit via Ajax. But we don’t have the form validation yet. We will use the help from two jquery plugins which are jquery validation and international telephone input plugins. The plugins have a good documentation. So I don’t need to cover in this post. You can visit the plugin sites and read it.

 

Here is my sample code for phone number validation by international telephone input plugin.

/**
 * Validate the phone number by intlTelInput plugin
 */
function validate_phone_newsletter() {
  var telInput = $("#mce-PHONE"),
    errorMsg = $("#error-msg"),

  telInput.intlTelInput({
    preferredCountries: ['th', 'us'],  // my site has 2 languages
    nationalMode: true,
    utilsScript: "<?php echo get_template_directory_uri(); ?>/js/utils.js"
  });

  var reset = function () {
    telInput.removeClass("error");
    errorMsg.addClass("hide");
  };

  // on blur: validate
  telInput.blur(function () {
    reset();
    if ($.trim(telInput.val())) {
    
      if (!telInput.intlTelInput("isValidNumber")) {
        telInput.addClass("error");
        errorMsg.removeClass("hide");
      }
      
    }
  });

  // on keyup / change flag: reset
  telInput.on("keyup change", reset);
}

Here is my sample code for the form validation by jquery validation plugin.

/**
 * Validate a form by jQuery.validate plugin
 * then submit form via ajax
 */
function validate_newsletter_form(){

  // prepare the message
  var language = $("input[name='language']").val();
  var firstname_message = '';
  var lastname_message = '';
  var phone_message = '';
  var email_message = '';


  if (language === 'th') {

    firstname_message = 'กรุณากรอกชื่อของคุณ';
    lastname_message = 'กรุณากรอกนามสกุลของคุณ';
    phone_message = 'กรุณากรอกเบอร์โทรศัพท์ของคุณ';
    email_message = 'กรุณากรอกอีเมลล์ของคุณ';
    
  } else {

    firstname_message = 'Please enter your first name';
    lastname_message = 'Please enter your last name';
    phone_message = 'Please enter your phone number';
    email_message = 'Please enter a valid email address';
    
  }


  // do validate by jquery.validate.js
  $form = $('#mc-embedded-subscribe-form');  
  $form.validate({
    rules: {
      FNAME: "required",
      LNAME: "required",
      PHONE: "required",
      EMAIL: "required"
    },
    highlight: function (element) {
      $(element).closest(".form-group").addClass("has-error");
    },
    unhighlight: function (element) {
      $(element).closest(".form-group").removeClass("has-error");
    },
    messages: {
      FNAME: firstname_message,
      LNAME: lastname_message,
      PHONE: phone_message,
      EMAIL: email_message
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function (error, element) {
      if (element.prop("id") === 'mce-PHONE') {
        element.parents(".form-group").find(".help-block").append(error);

      } else if (element.parent('.input-group').length) {
        error.insertAfter(element.parent());
        
      } else {
        error.insertAfter(element);
      }
    },
    submitHandler: function(form) {
      // validate is complete then submit a form

      if( $(".newsletter").find("#error-msg").hasClass("hide") ) {
        subscribe_mailchimp( $(form) );
      }
    }
  });  

}

And here is my sample code for submitting the form via ajax.

/**
 * Submit a form via Ajax
 * Data will send to MailChimp then MailChimp will return the result which is success or fail.
 */
function subscribe_mailchimp($form) {
    var $btn = $form.find("#mc-embedded-subscribe");
    $btn.val("<?php echo $lbl_submiting ?>");
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user.              
                alert(data.msg);
            } else {
                // Submit is success, shows some message to notify the user.
                $btn.val("<?php echo $lbl_submit ?>");
                alert('Thank you for Subscribing!');
            }
        }
    });
}

In javascript, you will add the code below.

$(document).ready( function () {
    validate_phone_newsletter();   
    validate_newsletter_form();     
});

That’s it. It looks like a long post but it is worth it to read them all. Many clients want to control the style and thank you page for the signup form from MailChimp. So their website will look professional. Hope my post will be useful for you.