WordPress user has role

In some situations it is very helpful to know whether a WordPress user has a specific role (or not). For example to show a different sidebar based on the user’s role or add a discount to the cart total when the current user is a reseller of your products and you want to give him a special price.

I wrote a simple function that retrieves the user object based on a user id and compares this to a user role that can be specified as an argument. It returns a boolean based on the match with the role. When leaving the $user_id blank it looks for the current logged in user.

 * Function to check if a user has a specific role
 * @param string $role the user role identifier
 * @param int $user_id a specific user id to check
function th_user_has_role( $role = '', $user_id = null ) {

   if ( is_numeric( $user_id ) ) {
      $user = get_user_by( 'id', $user_id );
   } else {
      $user = wp_get_current_user();

   if ( empty( $user ) )
      return false;

   return in_array( $role, (array) $user->roles );

Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals