Last active
December 30, 2024 17:11
-
-
Save dknauss/80f8bfd9fd6e09ef0e5f83bb572ef886 to your computer and use it in GitHub Desktop.
Expire idle WordPress user sessions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Set a short expiration for the user's auth/session cookie. | |
| add_filter ( 'auth_cookie_expiration', 'set_session_limit', 10, 3 ); | |
| function set_session_limit ( $expire, $user_id, $remember ) { | |
| $remember = false; // Turn off the "Remember Me" extended session limit for all users. | |
| return 300; // Set login session limit in seconds, 300 = 5 minutes | |
| } | |
| // Hook this function to the 'init' action to run on every page load. | |
| add_action( 'init', 'if_idle_reset_cookie_expiration' ); | |
| function if_idle_reset_cookie_expiration() { | |
| if ( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) === 'xmlhttprequest' ) { | |
| return; // Return if this is the heartbeat request. | |
| } | |
| if( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) { | |
| return; // Return if the user logs out. | |
| } | |
| if( isset( $_GET['loggedout'] ) && $_GET['loggedout'] == 'true' ) { | |
| return; // Return if the user is logged out. | |
| } | |
| if ( is_user_logged_in() ) { // Check if the user is logged in. | |
| wp_set_auth_cookie( get_current_user_id(), false ); // Extend the user's authentication cookie. | |
| } | |
| } | |
| // This filter sets the user session/auth cookie expiration to a short window of time, | |
| // and the action will keep renewing and extending the user session as long as there is | |
| // new (page refresh) activity. | |
| // | |
| // You can change the session limits, but you should keep them brief. Look out for | |
| // potential conflicts with other code specifying auth_cookie_expiration() limits. | |
| // | |
| // Sourced from Elliott Richmond (@eirichmond): | |
| // https://github.com/eirichmond/er-expire-user-cookie | |
| // | |
| // (For testing, debugging, and evaluation only — it seems to wreak havoc with the admin UX.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment