Question: How to get the currently logged WordPress user has role? In some situations it is very helpful to realise whether a WordPress user has a specific role has_role (or not). For We learn to simple example to show a various sidebar based Menu on the user’s roles plugin or include a deduction to the cart Based total when the current Active user is a distributor of your items as well as you want to give him a specific price.
I wrote a simple function that fetch the WP user object based on a user id as well as the differentiate this to a user Has roles that can be identify as parameters. It returns a Boolean based Data value Like as true or false on the exact match with the each role. When quit the main $user_id blank it counts for the Active current logged in user.
Get current user has role in WordPress
/** * Method to verify if a user has a specific role * * @param string $role the user role identifier * @param int $user_id a specific user id to verify */ function th_user_has_role( $role = '', $user_id = null ) { if ( is_numeric( $user_id ) ) { $wp_get_users_all_role = get_user_by( 'id', $user_id ); } else { $wp_get_users_all_role = wp_get_current_user(); } if ( empty( $wp_get_users_all_role ) ) return false; return in_array( $role, (array) $wp_get_users_all_role->roles ); }
How To Get An User Role In WordPress?
How to get an User Role as well as check if user is admin in WordPress. getting an user role have little methods. Let’s verify the function here to get word press user roles From database. For new current user you can use the below methods to fetch the current display user.
wordpress user has_role
function custom_get_current_user_role(){ $wp_get_users_all_role = ''; global $current_user, $wp_roles, $wpdb; get_currentuserinfo(); foreach ( $wp_roles->role_names as $role => $name ) : if ( current_user_can( $role ) ) $wp_get_users_all_role = $role; endforeach; return $wp_get_users_all_role; }
And the Above PHP Source code looks big enough to work WordPress Current Logged in users has roles, I will use a easy source code which is more simple as well as executes within the WordPress methods itself.
$user_details = new WP_User( $user_id ); $user_role= wp_sprintf_l( '%l', $user_details->roles ); echo $user_role;
You can use change the `$user_id` to current user ID to get current user with in it.
Web Programming Tutorials Example with Demo
Read :
Summary
You can also read about AngularJS, ASP.NET, VueJs, PHP.
I hope you get an idea about WordPress users has roles.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.