Force logout ALL users at a certain time

I'm wondering if it's possible to logout all users 2 times a day using the function wp_logout() ?

I see loads of plugins who can logout idled users but we want to log out every single users twice a day at

2PM and 10PM

Hope someone can help me with this.

Topic logout users Wordpress

Category Web


Managed to solve this issue myself by deleting the usermeta from the database directly by doing as follows:

$stmt = $dbh->prepare('DELETE FROM wp_usermeta WHERE meta_key=\'session_tokens\'');

This should be possible, WordPress provides the WP_Session_Tokens class to manage logged in sessions. Then it's just a matter of connecting it to the cron. The following is a simple plugin file which I think should do it. Add it to the plugins directory and it should start working. *not tested.

<?php
/*
Plugin Name: Logout Users
Description: Forces all users to be logged out twice a day.
Author: Tim Ross
Version: 1.0.0
Author URI: https://timrosswebdevelopment.com
*/

/**
 * Create hook and schedule cron job on plugin activation.
 * Schedule recurring cron event.
 */
function logout_users_plugin_activate() {
    $timestamp2pm = strtotime( '14:00:00' ); // 2:00 PM.
    $timestamp10pm = strtotime( '22:00:00' ); // 10:00 PM.
    // check to make sure it's not already scheduled.
    if ( ! wp_next_scheduled( 'myplugin_cron_hook' ) ) {
        wp_schedule_event( $timestamp2pm, 'daily', 'logout_users_plugin_cron_hook' );
        wp_schedule_event( $timestamp10pm, 'daily', 'logout_users_plugin_cron_hook' );
        // use wp_schedule_single_event function for non-recurring.
    }
}
register_activation_hook( __FILE__, 'logout_users_plugin_activate' );


/**
 * Unset cron event on plugin deactivation.
 */
function logout_users_plugin_deactivate() {
    wp_clear_scheduled_hook( 'logout_users_plugin_cron_hook' ); // unschedule event.
}
register_deactivation_hook( __FILE__, 'logout_users_plugin_deactivate' );

function logout_all_users() {
    // Get an instance of WP_User_Meta_Session_Tokens
    $sessions_manager = WP_Session_Tokens::get_instance();
    // Remove all the session data for all users.
    $sessions_manager->drop_sessions();
}

// hook function logout_users_plugin_cron_hook() to the action logout_users_plugin_cron_hook.
add_action( 'logout_users_plugin_cron_hook', 'logout_all_users' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.