How to automatically log out a user and redirect him to a login page with a custom message in WordPress

When any page is viewed, I need to make sure that the user ID is in a custom database table, and if the id is not present there, I want to log the user out and not allow him to see any content. I also want to display a custom message on the login page saying “You are not authorised to see this blog.”

I tried doing this with some of the wp logout/redirect functions, but I want this to be automatic on all pages across the wp site. Also I don’t know how to sent the custom message to the login page. I guess I could just set a POST value or something like that and modify the login page to check if that value is present.

Read More

Any help or tips on how to do this properly would be appreciated.

Related posts

Leave a Reply

1 comment

  1. Try following

    Put the code below in your theme templates.

        //Logic for checking whether the ID exists or not
        if(empty($id)){
           wp_logout();
        }
    

    Put following in your function.php

        //When the user is logged out redirect him/her to the login page with a custom parameter
        add_action('wp_logout','go_home');
        function go_home(){
          wp_redirect( '/wp-login.php?action=logout&custom-logout=yes' );
          exit();
        }
    
        //If the custom parameter is set display the message on the login screen
        if(!empty($_GET['custom-logout']) && strtolower($_GET['custom-logout']) == "yes"){
         function custom_login_message() {
             $message = '<p class="message">Add your message here...</p><br />';
             return $message;
         }
         add_filter('login_message', 'custom_login_message');
        }