The auth_cookie WordPress PHP filter allows you to modify the authentication cookie.
Usage
add_filter('auth_cookie', 'your_custom_function', 10, 5); function your_custom_function($cookie, $user_id, $expiration, $scheme, $token) { // your custom code here return $cookie; }
Parameters
- $cookie (string): The authentication cookie.
- $user_id (int): The User ID.
- $expiration (int): The time the cookie expires as a UNIX timestamp.
- $scheme (string): Cookie scheme used. Accepts ‘auth’, ‘secure_auth’, or ‘logged_in’.
- $token (string): User’s session token used.
More information
See WordPress Developer Resources: auth_cookie
Examples
Extend the authentication cookie expiration time
In this example, we extend the expiration time of the authentication cookie by 1 day.
add_filter('auth_cookie', 'extend_auth_cookie_expiration', 10, 5); function extend_auth_cookie_expiration($cookie, $user_id, $expiration, $scheme, $token) { $extended_expiration = $expiration + DAY_IN_SECONDS; return wp_generate_auth_cookie($user_id, $extended_expiration, $scheme, $token); }
Change the cookie scheme
In this example, we change the cookie scheme to ‘secure_auth’.
add_filter('auth_cookie', 'change_cookie_scheme', 10, 5); function change_cookie_scheme($cookie, $user_id, $expiration, $scheme, $token) { return wp_generate_auth_cookie($user_id, $expiration, 'secure_auth', $token); }
Add custom data to the authentication cookie
In this example, we add custom data to the authentication cookie.
add_filter('auth_cookie', 'add_custom_data_to_cookie', 10, 5); function add_custom_data_to_cookie($cookie, $user_id, $expiration, $scheme, $token) { $custom_data = '|custom_data_here'; return $cookie . $custom_data; }
Invalidate the authentication cookie for certain user roles
In this example, we invalidate the authentication cookie for users with the ‘subscriber’ role.
add_filter('auth_cookie', 'invalidate_auth_cookie_for_subscribers', 10, 5); function invalidate_auth_cookie_for_subscribers($cookie, $user_id, $expiration, $scheme, $token) { $user = get_userdata($user_id); if (in_array('subscriber', $user->roles)) { return ''; } return $cookie; }
Change the authentication cookie for a custom token
In this example, we generate a custom token and use it for the authentication cookie.
add_filter('auth_cookie', 'change_auth_cookie_token', 10, 5); function change_auth_cookie_token($cookie, $user_id, $expiration, $scheme, $token) { $custom_token = 'custom_token_here'; return wp_generate_auth_cookie($user_id, $expiration, $scheme, $custom_token); }