How do I log out users from a restricted page if they are already logged in on another device? [closed]

I would use AJAX to check if the user is logged in. You could use setInterval to check every 30 seconds (or whatever).

I tested the following code, and it works. First, create a file in your theme directory called ajax.js and put this code in it:

(function ( $ ) {
    var check_user_is_logged_in = function(){
        $.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: {action:'is_user_logged_in'},
            success:function(data) {
                if ( data == 'no' ) {
                    window.location.href = "http://mywebsite.com";
                }
            },
            error: function(errorThrown){
                console.log(errorThrown);
            }
        });
    };

    setInterval(function(){
        check_user_is_logged_in();
    }, 30000);
})( jQuery );

In the above code, change “mywebsite.com” to whatever URL you want to redirect logged out users to. You can also adjust 30000. That’s the number of milliseconds it should wait between checking.

Next, in your theme’s functions.php file, add this code:

function na_check_user_logged_in() {
    // Simply check if the user is logged in or not and echo 'yes' or 'no'
    echo ( is_user_logged_in() ) ? 'yes' : 'no';
    wp_die();
}

function na_enqueue_scripts(){
    // Enqueue our ajax.js script
    wp_enqueue_script( 'na_ajax_example', get_stylesheet_directory_uri().'/ajax.js', 'jquery');

    // Reveal the ajax_url for our script     
    wp_localize_script( 'na_ajax_example', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
};

add_action( 'wp_ajax_is_user_logged_in', 'na_check_user_logged_in' );
add_action( 'wp_ajax_nopriv_is_user_logged_in', 'na_check_user_logged_in' );
add_action( 'wp_enqueue_scripts', 'na_enqueue_scripts' );

Right now, this code will run on every page. You will need to edit the na_enqueue_scripts function and add some logic so it only enqueues the script on the protected pages.