1

I'm trying to configure the WordPress cookie expiration time, but for some reason it's not working. I went here:

https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/

And put the following hook based on the doc:

function init() {
    // ...
    $expiration = 60;
    apply_filters( 'auth_cookie_expiration', $expiration );
}

This code is called from a hook in my plugin's constructor:

add_action( 'init', array( $this, 'init' ) );

And I have verified that it runs.

I expected this to produce a cookie that expires in 60 seconds, but it doesn't. Instead it sets a regular expiration time of 48 hours (WP default). I suspect this might be because when the user actually logs in, it doesn't create this expiration date, and running this function later has no effect. I haven't yet figured out how to make it work though. Any help appreciated.

1

Note that you're not adding any filter callback with:

apply_filters( 'auth_cookie_expiration', $expiration );

Instead use:

add_filter( 'auth_cookie_expiration', $callback, 10, 3 );

where $callback is the appropriate filter callback that modifies the expiration.

Here's an example

add_filter( 'auth_cookie_expiration', function( $length, $user_id, $remember ) {
    return $length; // adjust this to your needs.
}, 10, 3 );

or to fit with your current class setup:

add_filter( 'auth_cookie_expiration', [ $this, 'set_auth_cookie_expiration' ], 10, 3 );

where set_auth_cookie_expiration() is the appropriate method, e.g.:

public function set_auth_cookie_expiration ( $length, $user_id, $remember ) 
{
    return $length; // adjust this to your needs.
}
  • Thanks, I saw the second parameter being a callback in some examples, but the main doc says it's an integer ($length). Why the discrepancy? Is this version-dependent? And if the parameters in the doc are wrong, what do the other two parameters stand for? Also, how do I pass params to the callback? – Ynhockey Jan 3 '18 at 14:43
  • 1
    I think you're just misunderstanding a little bit the apply_filters vs add_filter. We look at apply_filters() to see how to construct our callbacks in add_filter(). I updated the answer. Hope it explains it better. @Ynhockey – birgire Jan 3 '18 at 14:55
-1
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.