I want to send an email to users whose membership has expired 30 days after, one one email each, the data is in usermeta

WPTurbo » Snippets » I want to send an email to users whose membership has expired 30 days after, one one email each, the data is in usermeta
0

Created with:

Visibility: 

public

Creator: David Fletcher

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

<?php

namespace WPTurbo;

function wpturbo_send_expiration_emails() {
    global $wpdb;

    // Define the number of days for expiration
    $expiration_days = 30;
    $expiration_date = date( 'Y-m-d H:i:s', strtotime( "-{$expiration_days} days" ) );

    // Get users whose membership has expired 30 days ago
    $users = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT user_id FROM {$wpdb->usermeta} 
             WHERE meta_key = %s 
             AND meta_value < %s",
            'membership_expiration_date',
            $expiration_date
        )
    );

    // Get the admin email
    $admin_email = get_option( 'admin_email' );

    // Loop through each user and send email
    foreach ( $users as $user ) {
        $user_data = get_userdata( $user->user_id );

        if ( $user_data ) {
            $to = $user_data->user_email;

            if ( is_email( $to ) ) {
                $display_name = esc_html( $user_data->display_name );
                $subject = "Your Membership Has Expired";
                $message = "Dear {$display_name},nnYour membership expired 30 days ago. Please consider renewing your membership.nnThank you!";
                
                // Set up headers for BCC
                $headers = [];
                $headers[] = 'Bcc: ' . $admin_email;

                wp_mail( $to, $subject, $message, $headers );
            }
        }
    }
}

// Hook the function to a custom action or cron job
add_action( 'wpturbo_send_expiration_emails_hook', 'wpturbo_send_expiration_emails' );

// Schedule the event to run daily
if ( ! wp_next_scheduled( 'wpturbo_send_expiration_emails_hook' ) ) {
    wp_schedule_event( time(), 'daily', 'wpturbo_send_expiration_emails_hook' );
}
				

Make sure to test the scheduling feature and the email functionality in a staging environment before deploying it to a live site, as email configurations can vary based on server settings and hosting environments.

This setup will help you manage expired memberships more efficiently while keeping the admin informed.

Register an account to save your snippets or go Pro to get more features.