Skip to Content
Frontlane Studio
All Snippets
PHP WordPress November 14, 2024

Birthday Email Greetings Based on User Meta Data

A PHP snippet for Birthday Email Greetings Based on User Meta Data.

WordPress PHP

A PHP snippet for Birthday Email Greetings Based on User Meta Data.

function send_birthday_email($user_id) {
    // Get the user's birthday (assume it's stored in user meta as 'birthday' in Y-m-d format).
    $birthday = get_user_meta($user_id, 'birthday', true);
    if (!$birthday) return;

    // Check if today matches the user's birthday.
    $current_date = date('m-d');
    $user_birthday = date('m-d', strtotime($birthday));

    if ($current_date === $user_birthday) {
        $user = get_user_by('ID', $user_id);
        $subject = "Happy Birthday, {$user->display_name}!";
        $message = "<p>Dear {$user->display_name},</p>";
        $message .= "<p>Happy Birthday! We hope you have a wonderful day filled with joy and happiness!</p>";
        $message .= "<p>Best Wishes,</p><p>The Team</p>";
        $headers = array('Content-Type: text/html; charset=UTF-8');
        
        wp_mail($user->user_email, $subject, $message, $headers);
    }
}

function check_for_birthdays() {
    $users = get_users(array('meta_key' => 'birthday'));

    foreach ($users as $user) {
        send_birthday_email($user->ID);
    }
}

// Schedule daily check for birthdays.
if (!wp_next_scheduled('check_for_birthdays_hook')) {
    wp_schedule_event(time(), 'daily', 'check_for_birthdays_hook');
}
add_action('check_for_birthdays_hook', 'check_for_birthdays');