函数文档

wp_get_users_with_no_role()

💡 云策文档标注

概述

wp_get_users_with_no_role() 函数用于获取指定站点中无角色用户的用户ID数组。它支持多站点环境,通过数据库查询实现。

关键要点

  • 函数返回一个字符串数组,包含无角色用户的用户ID。
  • 参数 $site_id 可选,默认为当前站点ID,用于指定要查询的站点。
  • 在多站点环境中,函数会处理站点切换以正确获取角色名称。
  • 通过正则表达式匹配数据库中的用户能力元数据来筛选无角色用户。

代码示例

function wp_get_users_with_no_role( $site_id = null ) {
	global $wpdb;

	if ( ! $site_id ) {
		$site_id = get_current_blog_id();
	}

	$prefix = $wpdb->get_blog_prefix( $site_id );

	if ( is_multisite() && get_current_blog_id() !== $site_id ) {
		switch_to_blog( $site_id );
		$role_names = wp_roles()->get_names();
		restore_current_blog();
	} else {
		$role_names = wp_roles()->get_names();
	}

	$regex = implode( '|', array_keys( $role_names ) );
	$regex = preg_replace( '/[^a-zA-Z_|-]/', '', $regex );
	$users = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT user_id
			FROM $wpdb->usermeta
			WHERE meta_key = '{$prefix}capabilities'
			AND meta_value NOT REGEXP %s",
			$regex
		)
	);

	return $users;
}

注意事项

  • 函数从 WordPress 4.4.0 版本引入,4.9.0 版本添加了 $site_id 参数以支持多站点。
  • 在调用时需确保数据库表结构正确,特别是 usermeta 表中的 meta_key 格式。
  • 在多站点环境中使用非当前站点ID时,函数会临时切换站点,但会恢复原状态。

📄 原文内容

Gets the user IDs of all users with no role on this site.

Parameters

$site_idint|nulloptional
The site ID to get users with no role for. Defaults to the current site.

Default:null

Return

string[] Array of user IDs as strings.

Source

function wp_get_users_with_no_role( $site_id = null ) {
	global $wpdb;

	if ( ! $site_id ) {
		$site_id = get_current_blog_id();
	}

	$prefix = $wpdb->get_blog_prefix( $site_id );

	if ( is_multisite() && get_current_blog_id() !== $site_id ) {
		switch_to_blog( $site_id );
		$role_names = wp_roles()->get_names();
		restore_current_blog();
	} else {
		$role_names = wp_roles()->get_names();
	}

	$regex = implode( '|', array_keys( $role_names ) );
	$regex = preg_replace( '/[^a-zA-Z_|-]/', '', $regex );
	$users = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT user_id
			FROM $wpdb->usermeta
			WHERE meta_key = '{$prefix}capabilities'
			AND meta_value NOT REGEXP %s",
			$regex
		)
	);

	return $users;
}

Changelog

Version Description
4.9.0 The $site_id parameter was added to support multisite.
4.4.0 Introduced.