Posted By

chrisaiv on 09/13/14


Tagged

wordpress


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tryan326


Wordpress: Check current user's roles


 / Published in: PHP
 

Checks if a particular user has a role.

  1. /**
  2. * Checks if a particular user has a role.
  3. * Returns true if a match was found.
  4. *
  5. * http://codex.wordpress.org/Roles_and_Capabilities#Subscriber
  6. * http://docs.appthemes.com/tutorials/wordpress-check-user-role-function/
  7. * http://wordpress.org/support/topic/how-to-get-the-current-logged-in-users-role
  8. *
  9.  
  10. * @param string $role Role name.
  11. * @param int $user_id (Optional) The ID of a user. Defaults to the current user.
  12. * @return bool
  13. */
  14. function appthemes_check_user_role( $role, $user_id = null ) {
  15.  
  16. if ( is_numeric( $user_id ) )
  17. $user = get_userdata( $user_id );
  18. else
  19. $user = wp_get_current_user();
  20.  
  21. if ( empty( $user ) )
  22. return false;
  23.  
  24. return in_array( $role, (array) $user->roles );
  25. }
  26.  
  27.  
  28. // example use for the current user
  29. if ( appthemes_check_user_role( 'subscriber' ) ){
  30. show_admin_bar(false);
  31. } else {
  32. _e( "Sorry man, no luck.", 'appthemes' );
  33. }

Report this snippet  

You need to login to post a comment.