You are here

function mailchimp_segment_create in Mailchimp 7.5

Same name and namespace in other branches
  1. 7.3 mailchimp.module \mailchimp_segment_create()
  2. 7.4 mailchimp.module \mailchimp_segment_create()

Wrapper around MailchimpLists->addSegment().

Parameters

string $list_id: A MailChimp list id.

string $name: A label for the segment.

string $type: Can be 'static' or 'saved'.

array $segment_options: Array of options for 'saved' segments. See MailChimp API docs.

Return value

int ID of the new segment.

2 calls to mailchimp_segment_create()
MailchimpListsTestCase::testCreateSegment in modules/mailchimp_lists/tests/mailchimp_lists.test
Tests creation of a segment for a list.
mailchimp_lists_add_to_segment_action_submit in modules/mailchimp_lists/mailchimp_lists.module
Form handler for mailchimp_lists_add_to_segment_action_form().

File

./mailchimp.module, line 1247
Mailchimp module.

Code

function mailchimp_segment_create($list_id, $name, $type, $segment_options = NULL) {
  $segment_id = FALSE;
  try {

    /* @var \Mailchimp\MailchimpLists $mc_lists */
    $mc_lists = mailchimp_get_api_object('MailchimpLists');
    if (!$mc_lists) {
      throw new MailchimpException('Cannot add list segment without MailChimp API. Check API key has been entered.');
    }
    $parameters = array(
      'type' => $type,
    );
    if ($type == 'saved') {
      $parameters['options'] = $segment_options;
    }
    $result = $mc_lists
      ->addSegment($list_id, $name, $parameters);
    if (!empty($result->id)) {
      $segment_id = $result->id;
    }

    // Clear the segment cache:
    mailchimp_get_segments($list_id, TRUE);
  } catch (Exception $e) {
    watchdog('mailchimp', 'An error occurred creating segment @segment for list @list. "%message"', array(
      '@segment' => $name,
      '@list' => $list_id,
      '%message' => $e
        ->getMessage(),
    ), WATCHDOG_ERROR);
  }
  return $segment_id;
}