Skip to content

Logout user after 15 minutes of inactivity

Logout user after 15 minutes of inactivity

Logout user after 15 minutes of inactivity

After a pen test, a client requested a timeout for user inactivity while logged into WordPress’ admin area:

So, after a little codexing 🙂

Simply adds a time to a user meta field last_backend_action and if, after 15 minutes, it’ll kick you out with a custom message.

To use, upload to your theme directory, hopefully a child theme and include 'login-timeout.php'; to the top of your functions.php.

<?php
/**
* Automatically log out users after 15 minutes of inactivity
* ONLY when in the WordPress Backend.
*/
function mh_backend_inactivity_timeout()
{
// Only run if the user is logged in AND in the admin dashboard
if ( is_user_logged_in() && is_admin() )
{
$user_id = get_current_user_id();
$last_action = get_user_meta( $user_id, 'last_backend_action', true );
$timeout = 15 * 60; // 15 minute timeout
$current_time = time();
if ( $last_action && ( $current_time - $last_action > $timeout ) )
{
// Clear the timestamp so they don't get stuck in a loop
delete_user_meta( $user_id, 'last_backend_action' );
wp_logout();
// Redirect to login with a notification
wp_redirect( wp_login_url() . '?session_expired=true' );
exit;
}
// Update the timestamp only when they are in the backend
update_user_meta( $user_id, 'last_backend_action', $current_time );
}
}
// 'admin_init' ensures this only fires inside the /wp-admin/ area
add_action( 'admin_init', 'mh_backend_inactivity_timeout' );
add_filter( 'login_message', function( $message )
{
if ( isset( $_GET['session_expired'] ) )
{
$message = '<p class="message">Your session has expired due to 15 minutes of inactivity for security.</p>';
}
return $message;
} );

Comments (0)

Leave a Reply

Back To Top