WordPress Auto-Logout Script
This file contains a set of functions that implement an automatic logout feature for 'customer' role users in WordPress after a period of inactivity. It uses JavaScript to track user activity and a WordPress AJAX action to handle the logout process securely.
<?php function cwpai_logout_script() { if (is_user_logged_in() && current_user_can('customer')) { $logout_time = 30; // Set the logout time in seconds $logout_nonce = wp_create_nonce('cwpai_logout_nonce'); $logout_url = admin_url('admin-ajax.php?action=cwpai_logout&nonce=' . $logout_nonce); $script = " var cwpaiLogoutParams = { logoutTime: {$logout_time}, logoutUrl: '{$logout_url}' }; var idleTime = 0; var idleInterval; function resetIdleTime() { idleTime = 0; } function startIdleTimer() { idleInterval = setInterval(function() { idleTime++; if (idleTime >= cwpaiLogoutParams.logoutTime) { clearInterval(idleInterval); window.location.href = cwpaiLogoutParams.logoutUrl; } }, 1000); } function setupEventListeners() { ['mousemove', 'keydown', 'scroll', 'touchstart'].forEach(function(event) { document.addEventListener(event, resetIdleTime); }); window.addEventListener('beforeunload', function() { clearInterval(idleInterval); }); } setupEventListeners(); startIdleTimer(); "; return $script; } return ''; } function cwpai_enqueue_logout_script() { if (is_user_logged_in() && current_user_can('customer')) { //remember you must be a customer to test this - James wp_enqueue_script('cwpai-logout-script', '', [], '', true); wp_add_inline_script('cwpai-logout-script', cwpai_logout_script()); } } add_action('wp_enqueue_scripts', 'cwpai_enqueue_logout_script'); function cwpai_handle_logout() { check_ajax_referer('cwpai_logout_nonce', 'nonce'); if (is_user_logged_in() && current_user_can('customer')) { wp_logout(); wp_send_json_success(); } else { wp_send_json_error('User not logged in or not a customer.'); //you may want to make this as a wpdie or something with a better error display - James } wp_die(); } add_action('wp_ajax_cwpai_logout', 'cwpai_handle_logout');
Frequently Asked Questions
It automatically logs out customers who are inactive for a specified duration on a WordPress site.