MailPoet Custom Trigger Example for WP Zapier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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