Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Last active September 5, 2023 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewlimaza/7b44505e7d2eea6c1197024d7a3953e5 to your computer and use it in GitHub Desktop.
Save andrewlimaza/7b44505e7d2eea6c1197024d7a3953e5 to your computer and use it in GitHub Desktop.
MailPoet Custom Trigger Example for WP Zapier (Without creating the user in WordPress)
<?php
/**
* Add subscribers to multiple MailPoet lists when receiving data from Zapier with WP Zapier plugin.
* i.e. Add users to MailPoet lists via Zapier when added to Google Sheets.
* For full blog post visit - https://yoohooplugins.com/add-subscribers-mailpoet-zapier
*/
function add_subscribers_to_mailpoet_zapier( $user ) {
//If lists aren't passed through just bail.
if ( empty( $_REQUEST['lists'] ) ) {
return $user;
}
if ( class_exists(\MailPoet\API\API::class ) ) {
$mailpoet_api = \MailPoet\API\API::MP('v1');
$sub = array(
'email' => sanitize_email( $_REQUEST['email'] ),
// 'first_name' => sanitize_text_field( $_REQUEST['first_name'] ),
// 'last_name' => sanitize_text_field( $_REQUEST['last_name'] ),
// 'cf_my_field' => sanitize_text_field( $_REQUEST['my_field'] ) //Replace 'my_field' with your custom field name (optional).
);
// See if the user exists first.
try {
$subscriber = $mailpoet_api->getSubscriber( $sub['email'] );
} catch ( \Throwable $th ) {
// If the user doesn't exist, create them.
$subscriber = $mailpoet_api->addSubscriber( $sub );
}
// Try add the user to lists.
if ( $subscriber ) {
$user_id = $subscriber['id'];
$lists_id = explode( ',', $_REQUEST['lists'] );
$lists = array();
foreach( $lists_id as $key => $list_id ) {
$lists[] = intval( $list_id );
}
// add users to the lists.
try {
$subscribe = $mailpoet_api->subscribeToLists( $user_id, $lists );
} catch ( \Throwable $th ) {
echo 'unable to add to lists - ' . $th;
}
}
}
return $user;
}
add_filter( 'wp_zapier_custom_webhook', 'add_subscribers_to_mailpoet_zapier', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment