Categories
Functions

How to check if a user has a specific role or capability in WordPress

In many WordPress projects, you will need to check if a user has a specific role or capability. In this tutorial, I will provide custom functions to accomplish that.

custom function to check if the user has a specific role :

function wptips_has_user_role($check_role){
    $user = wp_get_current_user();
    if(in_array( $check_role, (array) $user->roles )){
		return true;
	}
    return false;
}

Once you have defined the above code in functions.php, you can check for a role as given below.

if(wptips_has_user_role('editor')){
// write your code here
}

WordPress core function to check if the user has a specific capability:

WordPress core has built-in function current_user_can , which can be used to check if currently logged in user has the given capability. an example is given below.

if(current_user_can('edit_posts')){
// write your code here
}

WordPress function references :

By Murali Kumar

I am a Full Stack Web Developer with over 12 years of experience. I love WordPress & WooCommerce.

If you need help of a WordPress developer for your website, get in touch now!.

Follow me on Twitter : @geekz

4 replies on “How to check if a user has a specific role or capability in WordPress”

Hello. Thanks for this. I have a custom function in my functions.php but I need to only run it if the logged in user has a specific role.
So I can see how to get the user role from this article. Do I just wrap my whole custom function inside an IF statement that says
If (user has role = editor) {
Custom function here
}

Would this work ?

Yes. ofcourse. You just have to use the function as given in the article.
if(wptips_has_user_role('editor')){
// call your custom function here
}

You can use the code with a simple conditional logic like below : if(wptips_has_user_role('editor') || wptips_has_user_role('customer')){
// call your function here
}

Leave a Reply

Your email address will not be published. Required fields are marked *