Using WordPress ‘auth_redirect’ PHP action

The auth_redirect WordPress PHP action fires before the authentication redirect.

Usage

add_action('auth_redirect', 'your_custom_function', 10, 1);

function your_custom_function($user_id) {
    // your custom code here

    return $user_id;
}

Parameters

  • $user_id (int): User ID.

More information

See WordPress Developer Resources: auth_redirect

Examples

Redirect user to a custom login page

Redirect users to a custom login page if they are not logged in.

add_action('auth_redirect', 'redirect_to_custom_login_page', 10, 1);

function redirect_to_custom_login_page($user_id) {
    if (0 === $user_id) {
        wp_redirect('/custom-login/');
        exit;
    }

    return $user_id;
}

Redirect users based on their role

Redirect users to different pages based on their role after login.

add_action('auth_redirect', 'redirect_users_based_on_role', 10, 1);

function redirect_users_based_on_role($user_id) {
    $user = get_userdata($user_id);
    $roles = $user->roles;

    if (in_array('administrator', $roles)) {
        wp_redirect('/admin-dashboard/');
    } elseif (in_array('subscriber', $roles)) {
        wp_redirect('/subscriber-dashboard/');
    }

    exit;
}

Restrict access to specific pages

Restrict access to a list of pages based on user roles.

add_action('auth_redirect', 'restrict_access_to_specific_pages', 10, 1);

function restrict_access_to_specific_pages($user_id) {
    $restricted_pages = array(10, 15, 20); // Page IDs
    $current_page_id = get_queried_object_id();

    if (in_array($current_page_id, $restricted_pages)) {
        $user = get_userdata($user_id);
        $roles = $user->roles;

        if (!in_array('administrator', $roles)) {
            wp_redirect(home_url());
            exit;
        }
    }

    return $user_id;
}

Log user activity

Log user activity before authentication redirect.

add_action('auth_redirect', 'log_user_activity', 10, 1);

function log_user_activity($user_id) {
    $user = get_userdata($user_id);
    $username = $user->user_login;

    // Log user activity
    error_log("User {$username} (ID: {$user_id}) logged in.");

    return $user_id;
}

Add custom user meta on login

Add custom user meta data on every login.

add_action('auth_redirect', 'add_custom_user_meta_on_login', 10, 1);

function add_custom_user_meta_on_login($user_id) {
    $login_count = get_user_meta($user_id, 'login_count', true);

    if ($login_count) {
        $login_count++;
    } else {
        $login_count = 1;
    }

    update_user_meta($user_id, 'login_count', $login_count);

    return $user_id;
}