user_can()
Checks whether a specified user has a specified capability.
Similar to current_user_can(), but this function takes a user ID or object as its first parameter. So we can check capability of specified user.
A role can be passed to this function to check against. But this practice is discouraged as it may produce unreliable results!
Also see map_meta_cap() function and map_meta_cap hook.
No Hooks.
Return
true|false
. Whether the user has the given capability.
Usage
user_can( $user, $capability );
- $user(int/WP_User) (required)
- User ID or object.
- $capability(string) (required)
- Capability name. See here the list of roles and capabilities.
- $object_id, ...(int)
ID of the object (for example, post or comment) to check the capability against. In this case, $capability should be a meta capability, not a primitive capability; for example, edit_post, but not edit_posts.
Read more about meta capabilities here map_meta_cap() – it maps meta capabilities to primitive capabilities based on the ID of the passed object and the name of the meta capability; and then this primitive capability can be checked against user capabilities.
Examples
#1 Проверим является ли юзер 3 Администратором
$user_id = 3; if( user_can( $user_id, 'manage_options' ) ){ // код }
#2 Check whether the user can delete posts
global $user_ID; if( ! user_can( $user_ID, 'delete_posts' ) ){ echo 'You don`t have such capability!'; }
#3 Check whether the user with ID 141 can edit the post with ID 1
This is an example of meta capability check.
if( user_can( 141, 'edit_post', 1 ) ){ echo 'You can edit this post'; }
Changelog
Since 3.1.0 | Introduced. |
Since 5.3.0 | Formalized the existing and already documented ...$args parameter by adding it to the function signature. |
user_can() user can code WP 6.6.2
function user_can( $user, $capability, ...$args ) { if ( ! is_object( $user ) ) { $user = get_userdata( $user ); } if ( empty( $user ) ) { // User is logged out, create anonymous user object. $user = new WP_User( 0 ); $user->init( new stdClass() ); } return $user->has_cap( $capability, ...$args ); }