Wordpress: Check current user's roles


/ Published in: PHP
Save to your folder(s)

Checks if a particular user has a role.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.