Using WordPress ‘invite_user’ PHP action

The invite_user WordPress PHP action fires immediately after an existing user is invited to join the site, but before the notification is sent.

Usage

add_action('invite_user', 'your_custom_function', 10, 3);
function your_custom_function($user_id, $role, $newuser_key) {
    // your custom code here
}

Parameters

  • $user_id (int) – The invited user’s ID.
  • $role (array) – Array containing role information for the invited user.
  • $newuser_key (string) – The key of the invitation.

More information

See WordPress Developer Resources: invite_user

Examples

Log user invitations

Log user invitations to a file for record keeping.

add_action('invite_user', 'log_user_invitation', 10, 3);
function log_user_invitation($user_id, $role, $newuser_key) {
    $user_info = get_userdata($user_id);
    $log_entry = date("Y-m-d H:i:s") . " - User {$user_info->user_login} (ID: {$user_id}) was invited with role: " . implode(', ', $role) . PHP_EOL;
    file_put_contents('user_invitations.log', $log_entry, FILE_APPEND);
}

Send custom email notification

Send a custom email notification to the site administrator when a user is invited.

add_action('invite_user', 'custom_invite_email_notification', 10, 3);
function custom_invite_email_notification($user_id, $role, $newuser_key) {
    $admin_email = get_option('admin_email');
    $user_info = get_userdata($user_id);
    $subject = "New user invitation: {$user_info->user_login}";
    $message = "A new user, {$user_info->user_login} (ID: {$user_id}), has been invited with the role: " . implode(', ', $role);
    wp_mail($admin_email, $subject, $message);
}

Add custom metadata to invited user

Add custom metadata to the invited user’s profile when they are invited.

add_action('invite_user', 'add_custom_user_meta', 10, 3);
function add_custom_user_meta($user_id, $role, $newuser_key) {
    update_user_meta($user_id, 'invitation_key', $newuser_key);
}

Track invitation count

Track the number of invitations sent by the site and store it as an option.

add_action('invite_user', 'track_invitation_count', 10, 3);
function track_invitation_count($user_id, $role, $newuser_key) {
    $invitation_count = get_option('invitation_count', 0);
    update_option('invitation_count', ++$invitation_count);
}

Set an expiration date for the invitation

Set an expiration date for the invitation and store it as user metadata.

add_action('invite_user', 'set_invitation_expiration', 10, 3);
function set_invitation_expiration($user_id, $role, $newuser_key) {
    $expiration_date = date('Y-m-d', strtotime('+30 days'));
    update_user_meta($user_id, 'invitation_expiration_date', $expiration_date);
}