How to delete user on logout and when session expires?

I am looking for a way to delete a user when they logout and when session expires…whatever one happens first?
Reason being is that all login authentication happens through an api to another company and checks if the user is a registered user with that company. Then the login will give them WP login authentication. All of this works, but I now want to delete users when they log out or when their session expires.
Thanks.

Related posts

3 comments

  1. So this is what I did…also keep in mind this is for a multisite and I am call calling this within a class. ‘Client’ is a custom user role that is create and given to users when they are created.

       function delete_user() {
            global $current_user;
    
            if(in_array('client', $current_user->roles )){
                if(!function_exists('wp_delete_user')) {
    
                    include(ABSPATH . "wp-admin/includes/ms.php");
                }
                wpmu_delete_user( $current_user->ID );
            }
        }
    add_action('clear_auth_cookie', 'delete_user');
    

    I do have one question…this works when the user logs out, but when will it run on its own. When the cookie times out?

  2. there you have mistake, you should have:

            .........
            if(!function_exists('wp_delete_user'))  {  include(ABSPATH . "wp-admin/includes/user.php");  }
            if(!function_exists('wpmu_delete_user')){  include(ABSPATH . "wp-admin/includes/ms.php");  }
            wpmu_delete_user( $current_user->ID );
            ..........
    
  3. I think first you have to update a meta before user makes logout.
    There will be a function that will run in init hook which will check for the meta value.
    If that meta value is present then it will remov the user whose id has that meta key value pair.

    function users_last_login() {
        $userinfo = wp_get_current_user();
        update_user_meta( $userinfo->ID, 'last_action', 'logout' );
    }
    add_action('clear_auth_cookie', 'users_last_login', 10);
    add_action('init', 'delete_users' );
    
    function delete_users() {
      $users = get_users(
                array(
                  'meta_key' => 'last_action',
                  'meta_value' => 'logout',
                ) 
              );
      if( !empty($users) ) {
        foreach( $users as $user ) {
          wp_delete_user($user->data->ID);
        }
      }
    }
    

Comments are closed.