函数文档

user_can()

💡 云策文档标注

概述

user_can() 函数用于检查特定用户是否拥有指定的权限。它支持元权限(如 edit_post)的检查,并可传递额外参数(如对象ID)进行更精确的验证。

关键要点

  • 函数返回布尔值,表示用户是否具备给定权限
  • 支持用户ID或WP_User对象作为第一个参数
  • 可处理元权限,通过map_meta_cap()映射到原始权限
  • 可选参数$args用于传递对象ID等额外信息

代码示例

user_can( $user->ID, 'edit_posts' );
user_can( $user->ID, 'edit_post', $post->ID );
user_can( $user->ID, 'edit_post_meta', $post->ID, $meta_key );

注意事项

  • 若用户未登录,函数会创建匿名用户对象进行处理
  • 从WordPress 5.3.0版本起,正式支持可变参数...$args
  • 相关函数包括current_user_can()和map_meta_cap()

📄 原文内容

Returns whether a particular user has the specified capability.

Description

This function also accepts an ID of an object to check against if the capability is a meta capability. Meta capabilities such as edit_post and edit_user are capabilities used by the map_meta_cap() function to map to primitive capabilities that a user or role has, such as edit_posts and edit_others_posts.

Example usage:

user_can( $user->ID, 'edit_posts' );
user_can( $user->ID, 'edit_post', $post->ID );
user_can( $user->ID, 'edit_post_meta', $post->ID, $meta_key );

Parameters

$userint|WP_Userrequired
User ID or object.
$capabilitystringrequired
Capability name.
$argsmixedoptional
Optional further parameters, typically starting with an object ID.

Return

bool Whether the user has the given capability.

Source

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 );
}

Changelog

Version Description
5.3.0 Formalized the existing and already documented ...$args parameter by adding it to the function signature.
3.1.0 Introduced.