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 :