Skip to content
Advertisement

WordPress $current_user returning blank

I’m trying to work with sessions in WordPress, it works when I login for the first time, but if I logout and login again the $current_user->user_login returns blank, can anyone help?

function register_session(){
    if(!session_id()){
        session_start();
    }
}
add_action('init','register_session');
function create_session(){
    global $current_user;
    $_SESSION['user'] = $current_user->user_login;
}
add_action('wp_login', 'create_session');

function finish_session(){
    session_destroy();
}
add_action('wp_logout', 'finish_session');

Advertisement

Answer

it looks like i was using the wrong hooks, i changed the code and now its working, leaving the code here if someone need.

function register_session(){
    if( !session_id() ){
        session_start();
    }
    $id = get_current_user_id();
    $user = get_userdata($id);
    $_SESSION["user"] = $user->user_login;
}
add_action('init','register_session');


//--------------finish the session after logout----------------------------
function finish_session() {
    session_destroy();
}
add_action('wp_logout', 'finish_session');
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement