This has got to be simple: how do I keep one user – my-user – logged in for a year? (I’m checking logged in cookies in the dev tools console).

Update 8/16/15

This works:

add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year', 10, 3 );

function keep_me_logged_in_for_1_year( $ttl, $user_id, $remember ) {
    if( 1 === $user_id )
        $ttl = YEAR_IN_SECONDS;
   return $ttl;
}

And with the array option, this works for multiple users:

add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year', 10, 3 );

function keep_me_logged_in_for_1_year( $ttl, $user_id, $remember ) {
    if( in_array( $user_id, array( 1, 2 ) ) )
        $ttl = YEAR_IN_SECONDS;
   return $ttl;
}

Update 8/12/15: Re: Rarst’s answer below: since get_currentuserinfo is pluggable, how would I use apply_filters in this context?

I’m getting a Call to undefined function get_currentuserinfo() error with this function below used in a simple plugin:

global $user_login;
   get_currentuserinfo();
   if ($user_login == "my-user") {

function keep_me_logged_in_for_1_year( $expirein ) {
   return 31556926; // 1 year in seconds
}
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );

}

But the Codex usage uses the global: https://codex.wordpress.org/Function_Reference/get_currentuserinfo

This, of course, keeps all users logged in for a year:

function keep_me_logged_in_for_1_year( $expirein ) {
   return 31556926; // 1 year in seconds
}
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );

1
1

get_currentuserinfo() is a pluggable function, it is not available during plugins load stage.

That aside you shouldn’t be adding filter conditionally, but use data provided by the filter. If you take a look at filter calls:

apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember )

$user_id is provided as second argument. You just have your filter listen for it and modify return conditionally on it.

Here’s an untested example:

add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year', 10, 3 );

function keep_me_logged_in_for_1_year( $ttl, $user_id, $remember ) {
    if( 123 === $user_id )
        $ttl = YEAR_IN_SECONDS;
   return $ttl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *