Saint Dave Saint Dave - 1 year ago 63
PHP Question

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.

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

Answer Source

Try following

Put the code below in your theme templates.

    //Logic for checking whether the ID exists or not

Put following in your function.php

    //When the user is logged out redirect him/her to the login page with a custom parameter
    function go_home(){
      wp_redirect( '/wp-login.php?action=logout&custom-logout=yes' );

    //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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download