Log Out Idle Users Automatically
Logs users out after a set time without any mouse, keyboard or scroll activity, counted across all their open tabs.
Opens WPIDE on
Code
// Minutes of inactivity before logout.
$wpide_idle_minutes = 30;
$wpide_idle_script = function () use ( $wpide_idle_minutes ) {
if ( ! is_user_logged_in() ) {
return;
}
$logout = wp_logout_url( add_query_arg( 'wpide_idle', '1', wp_login_url() ) );
?>
<script>
( function () {
var limit = <?php echo (int) $wpide_idle_minutes; ?> * 60000, key = 'wpideLastActivity', local = Date.now();
function touch() {
local = Date.now();
try { localStorage.setItem( key, String( local ) ); } catch ( e ) {}
}
function last() {
var shared = 0;
try { shared = parseInt( localStorage.getItem( key ), 10 ) || 0; } catch ( e ) {}
return Math.max( shared, local );
}
[ 'mousemove', 'keydown', 'scroll', 'click', 'touchstart' ].forEach( function ( evt ) {
window.addEventListener( evt, function () { if ( Date.now() - local > 15000 ) { touch(); } }, { passive: true } );
} );
touch();
setInterval( function () {
if ( Date.now() - last() > limit ) {
window.location.href = <?php echo wp_json_encode( $logout ); ?>;
}
}, 30000 );
} )();
</script>
<?php
};
add_action( 'admin_footer', $wpide_idle_script );
add_action( 'wp_footer', $wpide_idle_script );
add_filter( 'login_message', function ( $message ) use ( $wpide_idle_minutes ) {
if ( isset( $_GET['wpide_idle'] ) ) {
$message .= '<p class="message">' . esc_html( sprintf( 'You were logged out after %d minutes of inactivity.', $wpide_idle_minutes ) ) . '</p>';
}
return $message;
} );
Notes
This runs in the browser; the login cookie itself keeps its normal lifetime.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.