Back to Snippets

WordPress Custom Hook For User Registration Validation

PHP Database & Queries April 9, 2026

This snippet provides a custom WordPress hook to validate user registration, ensuring that users meet specific criteria before being allowed to register. It's useful for sites that require extra validation, such as email domain restrictions or custom role assignments. Key considerations include error handling and integration with existing registration processes.

Snippet Stats

Lines 36
Characters 1,524
Read 2 mins
php • 36 lines
// Hook into the user registration process to validate user input
add_action('user_register', 'custom_user_registration_validation');

function custom_user_registration_validation($user_id) {
    // Get the user object
    $user = get_userdata($user_id);

    // Check if the user's email domain is allowed
    $allowed_domains = array('example.com', 'anotherdomain.com');
    $user_email_domain = substr($user->user_email, strpos($user->user_email, '@') + 1);
    if (!in_array($user_email_domain, $allowed_domains)) {
        // If the domain is not allowed, delete the user and notify the administrator
        wp_delete_user($user_id);
        wp_mail('admin@example.com', 'Disallowed Email Domain', 'A user tried to register with a disallowed email domain: ' . $user_email_domain);
        return;
    }

    // Assign a custom role to the user
    $user->set_role('custom_role');

    // Log the registration for auditing purposes
    $log_message = 'User ' . $user->user_login . ' registered with email ' . $user->user_email;
    error_log($log_message);
}

// Also validate user input on the registration form submission
add_filter('registration_errors', 'custom_registration_form_validation', 10, 3);

function custom_registration_form_validation($errors, $sanitized_user_login, $user_email) {
    // Check for any existing users with the same email address
    if (email_exists($user_email)) {
        $errors->add('email_exists', 'An account with this email address already exists.');
    }

    return $errors;
}

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
PHP
Build performant WP_Query with combined meta and taxonomy filters, numeric ordering, and no_found_rows optimization.

Optimized WP_Query with Meta and Tax Filters

PHP
Create a custom database table with dbDelta on theme activation. Includes proper charset, indexes, and an insert helper function.

Create a Custom Database Table