Automated Inactive User Notification

Last updated 1 month ago

PHP
function send_inactive_user_reminders() {
    $inactive_users = get_users(array(
        'meta_key' => 'last_login',
        'meta_value' => strtotime('-6 months'),
        'meta_compare' => '<',
        'fields' => array('ID', 'user_email')
    ));

    foreach ($inactive_users as $user) {
        $subject = "We miss you!";
        $message = "Hello! We noticed you haven't logged in for a while. Come back and check out what's new!";
        wp_mail($user->user_email, $subject, $message);
    }
}

// Schedule the event to run monthly.
if (!wp_next_scheduled('send_inactive_user_reminders_hook')) {
    wp_schedule_event(time(), 'monthly', 'send_inactive_user_reminders_hook');
}

add_action('send_inactive_user_reminders_hook', 'send_inactive_user_reminders');

// Clear the event on plugin/theme deactivation.
register_deactivation_hook(__FILE__, function () {
    wp_clear_scheduled_hook('send_inactive_user_reminders_hook');
});

All code snippets are licensed GPLv2 or later unless otherwise stated.