Subscribe the Jetpack contact form to MailPoet

Jetpack now comes with a nice new feature allowing you to consent to subscribing to a newsletter when filling out their contact form. However, unless you’re using Creative Mail, it does… absolutely nothing. Not even mentions it in the email, in which case I could add them manually. So I started searching for a way to add it automatically:

UPDATE: be careful in implementing this without a CAPTCHA as spam emails will get bounced by MailPoet and too many bounces will disable your account.

/**
 * Subscribe the Jetpack contact form to the MailPoet newsletter
 */
add_action('grunion_after_message_sent', function ($post_id, $to, $subject, $message, $headers, $all_values, $extra_values) {
  if (!class_exists(\MailPoet\API\API::class) || !$all_values['email_marketing_consent']) return;

  $mailpoet_api = \MailPoet\API\API::MP('v1');

  $name = split_name($all_values['1_Name']); // make sure this field name is correct

  try {
    $mailpoet_api->addSubscriber([
      'email' => $all_values['2_Email'], // check this field too
      'first_name' => $name[0],
      'last_name' => $name[1],
    ], [1]); // use your own array of list ID's here
  } catch (\Exception $e) {
    $error = $e->getMessage();
  }
}, 10, 7);


/**
 * Split a name into first and last name
 *
 * @param [type] $name
 * @return array
 */
function split_name($name)
{
  $name = trim($name);
  $last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
  $first_name = trim(preg_replace('#' . preg_quote($last_name, '#') . '#', '', $name));
  return array($first_name, $last_name);
}

Credit this answer on Stack Overflow for the name splitting code.