Using WordPress ‘register_new_user’ PHP action

The register_new_user WordPress PHP action fires after a new user registration has been recorded.

Usage

add_action('register_new_user', 'your_custom_function');
function your_custom_function($user_id) {
    // your custom code here
}

Parameters

  • $user_id (int) – ID of the newly registered user.

More information

See WordPress Developer Resources: register_new_user

Examples

Send a welcome email to the new user

Send a welcome email to the new user after they have successfully registered.

add_action('register_new_user', 'send_welcome_email_to_new_user');
function send_welcome_email_to_new_user($user_id) {
    $user = get_userdata($user_id);
    $email = $user->user_email;
    $subject = 'Welcome to our website!';
    $message = 'Hello! Thank you for registering on our website. We hope you enjoy your experience.';
    wp_mail($email, $subject, $message);
}

Assign a custom role to a new user

Assign a custom role to a new user based on their email domain.

add_action('register_new_user', 'assign_custom_role_based_on_email');
function assign_custom_role_based_on_email($user_id) {
    $user = get_userdata($user_id);
    $email = $user->user_email;
    $domain = substr(strrchr($email, "@"), 1);

    if ($domain == 'example.com') {
        $user->set_role('custom_role');
    }
}

Log new user registrations

Log the user ID and registration timestamp for all new user registrations.

add_action('register_new_user', 'log_new_user_registrations');
function log_new_user_registrations($user_id) {
    $logfile = fopen('registration_log.txt', 'a');
    $log_entry = 'User ID: ' . $user_id . ', Registered at: ' . date('Y-m-d H:i:s') . "\n";
    fwrite($logfile, $log_entry);
    fclose($logfile);
}

Add a meta field to new users

Add a custom meta field called ‘signup_source’ to new users with a default value.

add_action('register_new_user', 'add_signup_source_meta_field');
function add_signup_source_meta_field($user_id) {
    $signup_source = 'default';
    add_user_meta($user_id, 'signup_source', $signup_source);
}

Send an admin notification for new user registrations

Notify the site administrator via email when a new user registers.

add_action('register_new_user', 'send_admin_notification_new_user');
function send_admin_notification_new_user($user_id) {
    $user = get_userdata($user_id);
    $email = get_option('admin_email');
    $subject = 'New user registration on your website';
    $message = 'A new user has registered on your website with the following details: Username - ' . $user->user_login . ', Email - ' . $user->user_email;
    wp_mail($email, $subject, $message);
}