0

One of our clients would like users with one specific user role to stay logged in for two weeks. He would like to automatically select the 'remember me' checkbox when logging in.

I have been able to solve this problem for 90% using the https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/ function and by adding some JS to automatically select the 'remember me' checkbox on the login page.

My problem:

  1. the cookie seems to be set on logging in for the first time (correct)
  2. but when I return the next day, the cookie isn't updated
  3. e.g. If I login on Jan 1st, I should stay logged in until Jan 15th
  4. When I login on Jan 2nd, the cookie should be refreshed / extended until Jan 16th

Do you have any idea if and how this extension is possible?

My problem seems to be similar to this one on how to change session expire time in wordpress:

See one the last comments: "I believe this solution will NOT address the 'inactivity' part of the question. This method will change cookie expiration but the user will be logged out regardless of whether or not they were active. WP does not seem to update the cookie expiration on user activity - it is set once on login"

heinvv
  • 1
  • 2

1 Answers1

0

You may can do it when the user visits any page, you will need to verify if the current user is logged in and met your desired user role, then update it's cookie ...

/* Renew cookie at every page load */
function renew_wp_cookie() {
    //Return early if its on login/logout page
    if(in_array($GLOBALS['pagenow'], array('wp-login.php'))) return;

    if (is_user_logged_in() && current_user_can('user_role')) {
        $current_logged_user = get_current_user_id();
        wp_set_auth_cookie($current_logged_user, true);
    }

}

add_action('init', 'renew_wp_cookie');
caiovisk
  • 3,667
  • 1
  • 12
  • 18
  • It works, but it seemed to give me problems while login out. Therefore I added an extra condition to make sure the code doesn't run on the logout page. I think this is what happened: the code force to cookie to be renewed and therefore it prevented the user from logging out if (is_archive() || is_front_page() ) { if (is_user_logged_in()) { $current_logged_user = get_current_user_id(); wp_set_auth_cookie($current_logged_user, true); } } – heinvv Feb 09 '18 at 07:17
  • You can check if the current page is the login page then return the function early, by including `if(in_array($GLOBALS['pagenow'], array('wp-login.php'))) return;`... I've edited the answer, please check it out. – caiovisk Feb 12 '18 at 00:12