Get the current role of a user in WordPress


On many occasions, when you are developing a theme, a WordPress plugin or directly a code for your own project or from a client, you need to know the current role of the user who is logged in.

Why? I can think of many situations but some recent ones:

  • In an online electronics store distinguish normal WooCommerce customers (customers) from another role created ex-professo for a development called wholesaler and sometimes we need to see what kind of user it is because the wholesaler has some advantages
  • In a travel agency with a private area, they needed to distinguish the administrator role from the user logged in
  • In an online store, certain custom created roles have a series of buttons in sight that others do not have

And like this … thousands of cases that can come to you. I leave the function and I comment as always:

function cod_get_role_current_user () {
  if (is_user_logged_in ()) {
    $ user = wp_get_current_user ();
    $ role = (array) $ user-> roles;
    return $ role[0];
  }
  else {
    return false;
  }
}

It is quite fast:

  • If the user is not logged in, it is sent false because it has no role, logically
  • If you are logged in, we collect the object with the current user
  • We save the list of user roles in $ role
  • We return the first role

What role format is returned? The format that WordPress uses internally is returned, that is to say for «Author», which is the Spanish string of «Author», the «slug» of the role is returned, ie: author. Two things before finishing.

Why roles is an array if a user can only have one role?

Actually a default user in WordPress can only have one role, but the structure that houses it is prepared to have several roles. It's a bit weird functionality but really this is valid:

$ someone = new WP_User ($ user_id);
$ someone-> add_role ('role-1');
$ someone-> add_role ('role-2');

The user $ someone would have two roles: role-1 and role-2 (apart from the ones he had before, which is why add_role is done for that.

Another thing is that these types of maneuvers help you because many of us only check the first element of the roles attribute.

Is there a simpler way to check certain roles as the administrator?

Apart from this, which implies: creating an object with the user and returning an element of an array, there is another simpler method to see the active user can play a capability. Every role is assigned a series of capabilities or capabilities The function is current_user_can and the typical example check if the user is an administrator, would be to call it with a typical administrator capability, as is manage_options:

current_user_can ('manage_options')

1 star

Loading…

We store the IPs from which the valuations are sent to avoid fraud



Leave a comment

Your email address will not be published. Required fields are marked *