函数文档

is_user_member_of_blog()

💡 云策文档标注

概述

is_user_member_of_blog() 函数用于检查指定用户是否为给定博客的成员。在单站点环境中,默认返回 true;在 Multisite 环境中,通过验证用户元数据中的 capabilities 键来判断成员资格。

关键要点

  • 函数接受两个可选参数:$user_id(用户ID,默认为当前用户)和 $blog_id(博客ID,默认为当前站点)。
  • 返回值类型为布尔值,true 表示用户是成员,false 表示不是或参数无效。
  • 在非 Multisite 环境中,函数直接返回 true,因为所有用户默认属于站点。
  • 函数内部处理包括参数验证、用户数据获取、站点状态检查以及通过 get_user_meta() 查询用户能力数据。

代码示例

$user_id = get_current_user_id();
$blog_id = 5;
if ( is_user_member_of_blog( $user_id, $blog_id ) ) {
    /*
     * The user is a member of the blog with ID 5.
     * We could do stuff here, like show them a link, etc.
     */
}

📄 原文内容

Finds out whether a user is a member of a given blog.

Parameters

$user_idintoptional
The unique ID of the user. Defaults to the current user.
$blog_idintoptional
ID of the blog to check. Defaults to the current site.

Return

bool

Source

function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
	global $wpdb;

	$user_id = (int) $user_id;
	$blog_id = (int) $blog_id;

	if ( empty( $user_id ) ) {
		$user_id = get_current_user_id();
	}

	/*
	 * Technically not needed, but does save calls to get_site() and get_user_meta()
	 * in the event that the function is called when a user isn't logged in.
	 */
	if ( empty( $user_id ) ) {
		return false;
	} else {
		$user = get_userdata( $user_id );
		if ( ! $user instanceof WP_User ) {
			return false;
		}
	}

	if ( ! is_multisite() ) {
		return true;
	}

	if ( empty( $blog_id ) ) {
		$blog_id = get_current_blog_id();
	}

	$blog = get_site( $blog_id );

	if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
		return false;
	}

	if ( 1 === $blog_id ) {
		$capabilities_key = $wpdb->base_prefix . 'capabilities';
	} else {
		$capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
	}
	$has_cap = get_user_meta( $user_id, $capabilities_key, true );

	return is_array( $has_cap );
}

Changelog

Version Description
MU (3.0.0) Introduced.

User Contributed Notes