Using WordPress ‘register_post’ PHP action

The register_post WordPress PHP action fires when submitting registration form data, before the user is created.

Usage

add_action('register_post', 'your_custom_function', 10, 3);

function your_custom_function($sanitized_user_login, $user_email, $errors) {
    // your custom code here
}

Parameters

  • $sanitized_user_login (string): The submitted username after being sanitized.
  • $user_email (string): The submitted email.
  • $errors (WP_Error): Contains any errors with submitted username and email, such as an empty field, an invalid username or email, or an existing username or email.

More information

See WordPress Developer Resources: register_post

Examples

Validate custom registration fields

add_action('register_post', 'validate_custom_fields', 10, 3);

function validate_custom_fields($sanitized_user_login, $user_email, $errors) {
    // Validate a custom field (e.g., "company_name")
    if (empty($_POST['company_name'])) {
        $errors->add('company_name_error', __('Please enter your company name.'));
    }
}

Set user role based on a custom field

add_action('register_post', 'set_user_role', 10, 3);

function set_user_role($sanitized_user_login, $user_email, $errors) {
    // Check if the user selected a specific role (e.g., "editor")
    if (isset($_POST['user_role']) && $_POST['user_role'] == 'editor') {
        // Add a custom meta key to store the user's role
        update_user_meta($user_id, 'user_role', 'editor');
    }
}

Send a custom email to the admin after registration

add_action('register_post', 'send_custom_email_to_admin', 10, 3);

function send_custom_email_to_admin($sanitized_user_login, $user_email, $errors) {
    // Check if there are no errors
    if (empty($errors->errors)) {
        $admin_email = get_option('admin_email');
        $subject = 'New user registration';
        $message = 'A new user has registered. Username: ' . $sanitized_user_login . ', Email: ' . $user_email;
        wp_mail($admin_email, $subject, $message);
    }
}

Check for specific email domain during registration

add_action('register_post', 'validate_email_domain', 10, 3);

function validate_email_domain($sanitized_user_login, $user_email, $errors) {
    // Check if the email domain is allowed
    $allowed_email_domains = array('example.com', 'example.org');
    $email_domain = substr(strrchr($user_email, "@"), 1);

    if (!in_array($email_domain, $allowed_email_domains)) {
        $errors->add('email_domain_error', __('Please use an allowed email domain.'));
    }
}

Store user’s IP address on registration

add_action('register_post', 'store_user_ip', 10, 3);

function store_user_ip($sanitized_user_login, $user_email, $errors) {
    // Get user's IP address
    $user_ip = $_SERVER['REMOTE_ADDR'];

    // Store user's IP address in a custom meta key
    update_user_meta($user_id, 'registration_ip', $user_ip);
}