函数文档

user_can_for_site()

💡 云策文档标注

概述

user_can_for_site() 函数用于检查指定用户在给定站点上是否拥有特定能力。它支持元能力检查,并可接受额外参数如对象ID。

关键要点

  • 函数用于验证用户在特定站点上的能力权限,适用于WordPress多站点环境。
  • 支持元能力(如 edit_post),通过 map_meta_cap() 映射到原始能力。
  • 参数包括用户ID或对象、站点ID、能力名称和可选参数(如对象ID)。
  • 返回布尔值,表示用户是否拥有该能力。
  • 内部实现会切换当前博客以进行权限检查,确保准确性。

代码示例

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

注意事项

  • 函数在WordPress 6.7.0版本中引入,需确保环境版本兼容。
  • 适用于多站点,使用前应通过 is_multisite() 检查环境。
  • 参数 $user 可以是用户ID或WP_User对象,函数内部会处理转换。
  • 如果用户未登录,函数会创建匿名用户对象进行权限检查。
  • 调用时可能涉及博客切换(switch_to_blog),需注意性能影响。

📄 原文内容

Returns whether a particular user has the specified capability for a given site.

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_for_site( $user->ID, $site_id, 'edit_posts' );
user_can_for_site( $user->ID, $site_id, 'edit_post', $post->ID );
user_can_for_site( $user->ID, $site_id, 'edit_post_meta', $post->ID, $meta_key );

Parameters

$userint|WP_Userrequired
User ID or object.
$site_idintrequired
Site ID.
$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_for_site( $user, $site_id, $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() );
	}

	// Check if the blog ID is valid.
	if ( ! is_numeric( $site_id ) || $site_id <= 0 ) {
		return false;
	}

	$switched = is_multisite() ? switch_to_blog( $site_id ) : false;

	$can = user_can( $user->ID, $capability, ...$args );

	if ( $switched ) {
		restore_current_blog();
	}

	return $can;
}

Changelog

Version Description
6.7.0 Introduced.