Configuring WordPress Auth Cookie Expiration

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

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.

2 Answers
2

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.
}

Leave a Comment