WordPress role is empty

happy Xmas and a happy New Year to all!

I’m trying to get the WordPress role for a logged user but I’m getting an empty array. Notice that the user seems to be logged, as the first conditional doesn’t get trigged.
Do somebody guess what could be happening?

if ( is_user_logged_in() ) 
{
    $user = new WP_User( $user_ID );
    if (!empty( $user->roles )) 
    {
        if(is_array($user->roles))
        {
            foreach ($user->roles as $role)
            echo $role;
        }
        else
        {
            echo "Not array";   
        }
    }
    else
    {
        echo "Is empty";    
    }
}
else
{
    echo "Not logged";  
}

Related posts

1 comment

  1. It could be that the $user_ID you’re passing into WP_User() is not set. Depending on the context this may or may not be set. You might be able to obtain it by inserting in the line above:

    global $user_ID;
    

    That would definitely be the case if you’re calling this from inside a function.

    or to be sure, you could try:

    $user_ID = get_current_user_id();
    

Comments are closed.