You can set the expiration time through the ‘auth_cookie_expiration’ filter, returning how many seconds until expiration. This will not update on every page request though. You could hook some early action like “init” and if the user is logged in, reset their auth cookie by calling set_auth_cookie()
again, even though it’s still valid.
When using the filter, your callback is passed the current user ID and the “remember” checkbox status, in addition to the default time. Normally when “remember” is checked, a much longer expiration time is set. You can choose to ignore this, but then the checkbox becomes meaningless.
How to call set_auth_cookie()
? Does it need any parameter? Or is this correct?
function set_cookie() {
if (is_user_logged_in()) {
set_auth_cookie();
}
}
add_action( 'init', 'set_cookie' );
Um, no, turns out that’s not even a function (it’s an action hook). Sorry, my bad. Serves me right to rely upon memory.
Please use wp_set_auth_cookie(). As you’ll see from the link, you must pass the user’s ID. There are a few other optional parameters as well.
Could u give me an example about how to reset the auth cookie on “init”? I’m still a bit confused about it
Earlier I said setting the auth cookie will override the earlier cookie. On second thought, lets first clear the old just to be safe. This does mean we should set the current user again since they would be forgotten by clearing the old.
function set_cookie() {
if (is_user_logged_in()) {
$user = wp_get_current_user();
wp_clear_auth_cookie();
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
}
}
add_action( 'init', 'set_cookie' );
You still need to use the ‘auth_cookie_expiration’ filter to shorten the expiration time of the cookie. The above code serves to reset the expiration time on every request.