WordPress at a glance

user_can() WP 3.1.0

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.

Works based on: WP_User::has_cap()

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 Check whether the user can delete posts

global $user_ID;
if( ! user_can( $user_ID, 'delete_posts' ) ){
	echo 'You don`t have such capability!';
}

#2 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.

Code of user can: wp-includes/capabilities.php WP 5.2.2

<?php
function user_can( $user, $capability ) {
	if ( ! is_object( $user ) ) {
		$user = get_userdata( $user );
	}

	if ( ! $user || ! $user->exists() ) {
		return false;
	}

	$args = array_slice( func_get_args(), 2 );
	$args = array_merge( array( $capability ), $args );

	return call_user_func_array( array( $user, 'has_cap' ), $args );
}

Related Functions

From tag: Roles capabilities

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register