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.
Navigate to Settings under the Audience tab on the Mailchimp site and click on Audience fields and |MERGE| tags
Click on Add A Field button at the bottom of the page and you will be presented with a list of field types.
You can select the type of field you want. In this example we shall select Text.
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>
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.