The added_existing_user WordPress PHP action fires immediately after an existing user is added to a site.
Usage
add_action('added_existing_user', 'your_custom_function', 10, 2);
function your_custom_function($user_id, $result) {
// Your custom code here
}
Parameters
$user_id(int): User ID.$result(true|WP_Error): True on success or a WP_Error object if the user doesn’t exist or could not be added.
More information
See WordPress Developer Resources: added_existing_user
Examples
Send a welcome email to the user
Send a welcome email to the user after they’ve been added to the site.
add_action('added_existing_user', 'send_welcome_email', 10, 2);
function send_welcome_email($user_id, $result) {
if (true === $result) {
// Get user data
$user_info = get_userdata($user_id);
// Compose welcome email
$subject = 'Welcome to Our Site!';
$message = 'Hi ' . $user_info->display_name . ",\n\nWelcome to our site! We're glad to have you on board.";
// Send email
wp_mail($user_info->user_email, $subject, $message);
}
}
Log user addition
Log the addition of an existing user to a site in a custom log file.
add_action('added_existing_user', 'log_user_addition', 10, 2);
function log_user_addition($user_id, $result) {
if (true === $result) {
// Log message
$log_message = 'User ' . $user_id . ' has been added to the site.';
// Write to log file
error_log($log_message, 3, 'user_addition.log');
}
}
Assign a default role
Assign a default role to the user after they’ve been added to the site.
add_action('added_existing_user', 'assign_default_role', 10, 2);
function assign_default_role($user_id, $result) {
if (true === $result) {
// Set default role
$default_role = 'subscriber';
// Assign role to user
$user = new WP_User($user_id);
$user->set_role($default_role);
}
}
Notify admin
Notify the admin via email when a new user is added to the site.
add_action('added_existing_user', 'notify_admin_of_user_addition', 10, 2);
function notify_admin_of_user_addition($user_id, $result) {
if (true === $result) {
// Get admin email
$admin_email = get_option('admin_email');
// Compose notification email
$subject = 'New User Added to the Site';
$message = 'A new user (ID: ' . $user_id . ') has been added to the site.';
// Send email
wp_mail($admin_email, $subject, $message);
}
}
Add user meta
Add custom user meta to the user after they’ve been added to the site.
add_action('added_existing_user', 'add_custom_user_meta', 10, 2);
function add_custom_user_meta($user_id, $result) {
if (true === $result) {
// Define custom user meta
$custom_meta = array(
'user_bio' => 'This is a custom user bio.',
'user_social_links' => array(
'twitter' => 'https://twitter.com/username',
'linkedin' => 'https://linkedin.com/in/username'
)
);
// Add custom user meta
foreach ($custom_meta as $meta_key => $meta_value) {
update_user_meta($user_id, $meta_key, $meta_value);
}
}
}