简体   繁体   English

在WordPress中扩展auth_cookie_expiration cookie

[英]Extend auth_cookie_expiration cookie in WordPress

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. 通过使用https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/函数并添加一些JS自动选择登录页面上的“记住我”复选框,我已经能够解决90%的问题。

My problem: 我的问题:

  1. the cookie seems to be set on logging in for the first time (correct) Cookie似乎是首次登录时设置的(正确)
  2. but when I return the next day, the cookie isn't updated 但是第二天返回时,cookie不会更新
  3. eg If I login on Jan 1st, I should stay logged in until Jan 15th 例如,如果我在1月1日登录,则应保持登录状态,直到1月15日
  4. When I login on Jan 2nd, the cookie should be refreshed / extended until Jan 16th 当我在1月2日登录时,Cookie应该刷新/延长至1月16日

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 : 我的问题似乎与此有关如何在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" 请参阅最后一条评论:“我相信此解决方案将无法解决问题的'非活动'部分。此方法将更改Cookie的有效期,但无论用户是否处于活动状态,都将注销用户。WP似乎无法根据用户活动更新cookie过期-登录后设置一次”

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 ... 您可以在用户访问任何页面时执行此操作,您需要验证当前用户是否已登录并符合所需的用户角色,然后更新它的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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM