• Resolved Muhammad Naufal

    (@falkia34)


    How to set user auth cookie expiration based on the latest user activity time? Because i want user to be logged out after a while of inactivity.

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator bcworkz

    (@bcworkz)

    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.

    Thread Starter Muhammad Naufal

    (@falkia34)

    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' );
    
    Moderator bcworkz

    (@bcworkz)

    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.

    Thread Starter Muhammad Naufal

    (@falkia34)

    Could u give me an example about how to reset the auth cookie on “init”? I’m still a bit confused about it

    Moderator bcworkz

    (@bcworkz)

    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.

    Thread Starter Muhammad Naufal

    (@falkia34)

    Thanks, I got it

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Auth Cookie Expiration’ is closed to new replies.