Home / Archive / MemberPress: Filter Email Recipients Based on Expired Memberships
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Filter Email Recipients Based on Expired Memberships

The code snippet updates the email recipient lists by removing email addresses of users whose membership subscriptions expired. This will be applied to all emails that contain a specified phrase or term in the email subject.

The sample code will be applied to the emails containing the Subscription renewal phrase in the email subject.

Code Preview
php
<?php
add_filter('mepr-wp-mail-recipients', function($recipients, $subject, $message, $headers) {
    
    if (strpos($subject, 'Subscription renewal') !== false) {
        foreach ($recipients as $key => $recipient) {
            // Extract the email address from the recipient field
            $regExp = "/<([^>]+)>/";
            preg_match($regExp, $recipient, $matches);
            $recipient = $matches[1];
            $wp_user = get_user_by('email', $recipient);
            if ($wp_user) {
                $user_id = $wp_user->ID;
                // Get the MemberPress user object
                $user = new MeprUser($user_id);
                // Retrieve all subscriptions (active and expired)
                $all_subs = $user->active_product_subscriptions('ids', true, false);
                // Retrieve only active subscriptions
                $active_subs = $user->active_product_subscriptions('ids', true);
                // Calculate expired subscriptions
                $expired_subs = array_diff($all_subs, $active_subs);
                // If the user has expired subscriptions, remove them from the recipients
                if (! empty($expired_subs)) {
                    unset($recipients[$key]); // Exclude the recipient
                    break;
                }
            }
        }
    }
    
    return $recipients;
}, 9999, 4);

Comments

Add a Comment