Using WordPress ‘auth_cookie_valid’ PHP action

The auth_cookie_valid WordPress PHP action fires once an authentication cookie has been validated. It is used to perform additional tasks or checks after the cookie validation process.

Usage

add_action('auth_cookie_valid', 'your_custom_function', 10, 2);

function your_custom_function($cookie_elements, $user) {
    // your custom code here
}

Parameters

  • $cookie_elements (string[]): Authentication cookie components.
    • username (string): User’s username.
    • expiration (string): The time the cookie expires as a UNIX timestamp.
    • token (string): User’s session token used.
    • hmac (string): The security hash for the cookie.
    • scheme (string): The cookie scheme to use.
  • $user (WP_User): User object.

More information

See WordPress Developer Resources: auth_cookie_valid

Examples

Log successful logins

Log each successful user login to a custom table in the database.

add_action('auth_cookie_valid', 'log_successful_login', 10, 2);

function log_successful_login($cookie_elements, $user) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'successful_logins';

    $wpdb->insert(
        $table_name,
        array(
            'username' => $cookie_elements['username'],
            'login_time' => current_time('mysql')
        )
    );
}

Custom user greeting

Display a custom greeting for the user after a successful login.

add_action('auth_cookie_valid', 'custom_user_greeting', 10, 2);

function custom_user_greeting($cookie_elements, $user) {
    set_transient('user_greeting_' . $user->ID, 'Welcome, ' . $user->display_name . '!', 60);
}

Increase user login count

Increase the user login count each time a user logs in.

add_action('auth_cookie_valid', 'increase_user_login_count', 10, 2);

function increase_user_login_count($cookie_elements, $user) {
    $login_count = (int) get_user_meta($user->ID, 'login_count', true);
    update_user_meta($user->ID, 'login_count', ++$login_count);
}

Apply custom user role capabilities

Modify the user capabilities based on a custom user role.

add_action('auth_cookie_valid', 'apply_custom_user_role_capabilities', 10, 2);

function apply_custom_user_role_capabilities($cookie_elements, $user) {
    if (in_array('custom_role', $user->roles)) {
        $user->add_cap('custom_capability');
    }
}

Restrict access based on IP

Restrict user access to the website based on the user’s IP address.

add_action('auth_cookie_valid', 'restrict_access_based_on_ip', 10, 2);

function restrict_access_based_on_ip($cookie_elements, $user) {
    $allowed_ips = array('192.168.1.1', '192.168.1.2');
    $user_ip = $_SERVER['REMOTE_ADDR'];

    if (!in_array($user_ip, $allowed_ips)) {
        wp_logout();
        wp_redirect(wp_login_url());
        exit;
    }
}