Reading:
Mailchimp API - Add and Submit Custom Audience Field

Mailchimp API - Add and Submit Custom Audience Field

Metamug
Mailchimp API - Add and Submit Custom Audience Field

We have seen how to add subscribers to Mailchimp using PHP in this article. Mailchimp also allows you to add custom fields to your audience forms. In this article, we shall see how to add an audience text field and make a request to Mailchimp using PHP.

Add a Merge field

  1. Navigate to Settings under the Audience tab on the Mailchimp site and click on Audience fields and |MERGE| tags Mailchimp settings

  2. Click on Add A Field button at the bottom of the page and you will be presented with a list of field types. Custom field types

  3. You can select the type of field you want. In this example we shall select Text.

  4. We shall enter the Field Label as Comment and the field tag as COMMENT. The field tag will be used in the API request to Mailchimp.

Create Custom Field

Create HTML Form

Let us create a form which takes comments Name, Email, Phone and Comments from the user.

<form action="submit.php" method="POST">
    <textarea name="comment" class="form-control" placeholder="Add your comments"></textarea>
    <input type="text" name="name"  class="form-control" placeholder="Full Name" required />
    <input type="email" name="email"  class="form-control" placeholder="Email" required/>
    <input type="number" name="phone" class="form-control" placeholder="Phone (optional)"/>
    <input class="btn btn-info" type="submit" name="submit" value="Submit"/>
</form>

Make API Request

The Mailchimp API accepts merge fields in JSON format as follows

{
    "email_address":"abc@gmail.com",
    "status":"subscribed",  
    "merge_fields": {
        "FNAME": "John Doe",
        "PHONE": "97******20"
        "COMMENT": "Your comments"
    }
}

Note here that the merge field name COMMENT in the JSON is the same as the field tag entered while creating the field.

The form data can be converted to JSON in PHP and sent to the Mailchimp API as follows

submit.php

$postData = array(
    "email_address" => $_POST["email"],
    "status" => "subscribed",
    "merge_fields" => array(
        "FNAME"=> $_POST["name"],
        "PHONE"=> $_POST["phone"],
        "COMMENT" => $_POST["comment"]
    )
);

// Setup cURL
$ch = curl_init('https://us20.api.mailchimp.com/3.0/lists/'.$list_id.'/members/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: apikey '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);

View custom field data The newly added custom field will be visible on Mailchimp and you can view the submitted data.

Custom field data



Icon For Arrow-up
Comments

Post a comment