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

  • Home
  • 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 :

4 Comments

  1. Adnaan Qureshi

    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 ?

    Reply
    • Murali Kumar

      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
      }

      Reply
      • Ty

        How do you do this for more than one user role? I have a function I want to execute for two different user roles

        Reply
        • Murali Kumar

          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
          }

          Reply

Leave a comment