How to get current user role in WordPress

This article shows how to get the user role of the current user in WordPress from within the loop using PHP code.

WordPress is a very dynamic and flexible platform. You can use it for pretty much anything. When writing any custom code for your WordPress website, it’s important to accurately identify and authenticate the user login that is executing the code.

WordPress offers a user accounts functionality with user role interface for users to create and manage their profiles. If a user has a role of Administrator, Editor or Author role, that means you can let him or her to update their profile information from the WordPress dashboard. Moreover, WordPress itself defines default roles using the global variable $wp_roles . You can edit these roles by adding or removing capabilities for each role or create new custom user role.

wordpress get current user role

WordPress offers many functions for checking the current user role of a user. Using these functions, you can easily decide what content, functionality, or actions should be available to a user in a certain user role. In this article, we’ll take a look at how you can use these functions to determine what content is available for any given user on your WordPress website.

Using these functions, you can easily decide what content, functionality, or actions should be available to a user in a certain user role.

There is no official WordPress function for giving a user a specific WordPress user role, so you need to write your own. Here’s an example custom function that you can use to check if a user can view a page or post.

You will need to add this short piece of code to the functions.php file in your active child theme or you could use a Snippets plugin to add the code:

 

In the code snippet above, we first check if the user is logged in. Than we use the wp_get_current_user to return the WP_User object of the current user. After that we can access the user role(s) via $user->roles. We return the roles in the same format as specified above (as an array). This is because a user can have more than one WordPress user role including custom user role.

You just need to add two lines of code to the functions.php file of your theme, and you can echo the current user role of the logged-in user so you can display it anywhere in your theme. If you want to test the code you can hook it to the wp_header and print it out to test if everything works properly:

 

Conclusion

WordPress role and capabilities are an important part of every WordPress site as they allow us to securely control access to content, website functionality and access to custom capability, depending on the user type. In this short tutorial we showed you how to get the user role of the current user in WordPress programmatically.