skip to Main Content

I have a code to get username and writes it to a log file when you logout of wordpress but it has stopped working when i updated my wordpress core to 5.7.
When you log out the username is no longer written to the file. Maybe something wrong with my hook. This is my code:

        function get_username(){
         if(is_user_logged_in()){   
         $active_user = wp_get_current_user();           
         $username = $active_user->user_login;
         $username = "User's username: ".$username;
         log_file_setup($username);
         }
        }


      add_action('wp_logout', 'get_username',1);  

2

Answers


  1. Chosen as BEST ANSWER

    I think i got it

    i changed the hook from:

     add_action( 'wp_logout', 'get_username', 1 );
    

    to

      add_action('clear_auth_cookie', 'get_username',1); 
    

    Any other suggestions are welcome


  2. You can use clear_auth_cookie function to get username.

    function users_last_login() {
        if(is_user_logged_in()){   
            $active_user = wp_get_current_user();           
            $username    = $active_user->user_login;
            $username    = "User's username: ".$username;
            update_user_meta( $active_user->ID, 'logout_time', date('Y-m-d H:i:s') );
            log_file_setup($username);
        }
    }
    add_action( 'clear_auth_cookie', 'get_username_on_logout', 10 );
    

    Or you can use template_redirect

    function get_username_on_template_redirect() {
        if ( isset( $_GET['action'] ) && $_GET['action'] == 'logout' && is_user_logged_in() ) {
            $active_user = wp_get_current_user();           
            $username    = $active_user->user_login;
            $username    = "User's username: ".$username;
            update_user_meta( $active_user->ID, 'logout_time', date('Y-m-d H:i:s') );
            log_file_setup($username);
        }
    }
    
    add_action( 'template_redirect', 'get_username_on_template_redirect' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search