Simple wordpress function to check user role, check if user role is admin or editor, all user roles, easy way to check user role in wordpress.
How To Check User Role
using is_user_logged_in() function and get_current_user_id() function and get_userdata() function, we will check user role in wordpress easily, firstly we will check if current user is logged in or not, after that we will get current user ID and get current user data, finally we will check the role.
Check User Role Function
Copy function code and paste it in your functions.php file, function code:
function WPTime_check_user_role($role_name){ if( is_user_logged_in() ){ // check if user is logged in $get_user_id = get_current_user_id(); // get user ID $get_user_data = get_userdata($get_user_id); // get user data $get_roles = implode($get_user_data->roles); if( $role_name == $get_roles ){ // check if role name == user role return true; } } }
Usage
In “$role_name” parameter, enter role name, for example:
if ( WPTime_check_user_role('administrator') ){ // check if user is admin, role name is 'administrator' // user is admin! do something .. }else{ // user is not admin! do something .. } // Another example if ( WPTime_check_user_role('editor') ){ // check if user is editor, role name is 'editor' // user is editor! do something .. }else{ // user is not editor! do something .. }
Names Of Roles
This is roles names, use it in “$role_name” parameter:
- administrator.
- editor.
- author.
- contributor.
- subscriber.
Where Can I Check User Role
In any file or any action or any function, for example in footer.php file or header.php file, or any file, or in wp_head() action or in wp_footer() action, or any action or function.