add_user_to_blog()
云策文档标注
概述
add_user_to_blog() 函数用于将用户添加到指定博客并分配角色,适用于多站点环境。它自动处理博客切换,返回 true 或 WP_Error 对象。
关键要点
- 函数参数:$blog_id(博客ID,整数)、$user_id(用户ID,整数)、$role(用户角色,字符串),均为必填。
- 返回值:成功时返回 true,失败时返回 WP_Error 对象(如用户不存在或无法添加)。
- 不检查用户是否已是博客成员,直接设置角色;如需避免覆盖,应先使用 is_user_member_of_blog() 检查。
- 自动调用 switch_to_blog() 切换博客,无需手动切换,并在返回前恢复当前博客。
- 内部使用 get_userdata() 验证用户,并通过 'can_add_user_to_blog' 过滤器控制添加权限。
- 触发 'add_user_to_blog' 动作钩子,便于开发者扩展功能。
代码示例
// 示例:将用户ID为123的用户添加到博客ID为456的博客,角色为'subscriber'
$result = add_user_to_blog( 456, 123, 'subscriber' );
if ( is_wp_error( $result ) ) {
// 处理错误
echo $result->get_error_message();
} else {
// 成功添加
echo '用户已成功添加。';
}注意事项
- 函数不验证用户是否已存在博客中,直接设置角色,可能覆盖现有角色。
- 依赖 WordPress 多站点功能,仅在启用多站点时有效。
- 内部使用缓存清理函数(如 clean_user_cache()),确保数据一致性。
原文内容
Adds a user to a blog, along with specifying the user’s role.
Description
Use the ‘add_user_to_blog’ action to fire an event when users are added to a blog.
Parameters
$blog_idintrequired-
ID of the blog the user is being added to.
$user_idintrequired-
ID of the user being added.
$rolestringrequired-
User role.
Source
function add_user_to_blog( $blog_id, $user_id, $role ) {
switch_to_blog( $blog_id );
$user = get_userdata( $user_id );
if ( ! $user ) {
restore_current_blog();
return new WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) );
}
/**
* Filters whether a user should be added to a site.
*
* @since 4.9.0
*
* @param true|WP_Error $retval True if the user should be added to the site, error
* object otherwise.
* @param int $user_id User ID.
* @param string $role User role.
* @param int $blog_id Site ID.
*/
$can_add_user = apply_filters( 'can_add_user_to_blog', true, $user_id, $role, $blog_id );
if ( true !== $can_add_user ) {
restore_current_blog();
if ( is_wp_error( $can_add_user ) ) {
return $can_add_user;
}
return new WP_Error( 'user_cannot_be_added', __( 'User cannot be added to this site.' ) );
}
if ( ! get_user_meta( $user_id, 'primary_blog', true ) ) {
update_user_meta( $user_id, 'primary_blog', $blog_id );
$site = get_site( $blog_id );
update_user_meta( $user_id, 'source_domain', $site->domain );
}
$user->set_role( $role );
/**
* Fires immediately after a user is added to a site.
*
* @since MU (3.0.0)
*
* @param int $user_id User ID.
* @param string $role User role.
* @param int $blog_id Blog ID.
*/
do_action( 'add_user_to_blog', $user_id, $role, $blog_id );
clean_user_cache( $user_id );
wp_cache_delete( $blog_id . '_user_count', 'blog-details' );
restore_current_blog();
return true;
}
Hooks
- do_action( ‘add_user_to_blog’, int $user_id, string $role, int $blog_id )
-
Fires immediately after a user is added to a site.
- apply_filters( ‘can_add_user_to_blog’, true|WP_Error $retval, int $user_id, string $role, int $blog_id )
-
Filters whether a user should be added to a site.
Changelog
| Version | Description |
|---|---|
| MU (3.0.0) | Introduced. |
Skip to note 2 content
Codex
Example