WordPress功能函數(shù)add_user_to_blog()
wordpress功能函數(shù)add_user_to_blog(),向博客添加用戶,并指定用戶的角色。
用法:
add_user_to_blog( int $blog_id, int $user_id, string $role )
描述:
當(dāng)用戶被添加到博客時,使用' add_user_to_blog '動作來觸發(fā)一個事件。
參數(shù):
$blog_id
(int) (必需) 用戶要添加到的博客的ID。
$user_id
(int) (必需) 添加的用戶ID。
$role
(string) (必需) 您希望用戶擁有的角色。
返回
(true|WP_Error)成功時為true,如果用戶不存在或無法添加,則為WP_Error對象。
更多信息
- 在設(shè)置角色之前,它不會檢查用戶是否已經(jīng)是博客的成員。如果您不想覆蓋已經(jīng)是博客成員的用戶的角色,可以使用is_user_member_of_blog()首先檢查。
- 在調(diào)用這個函數(shù)之前,您不需要調(diào)用switch_to_blog()來切換到您想要添加用戶的博客。該函數(shù)將切換到博客本身,并在返回之前還原當(dāng)前博客。
來源:
文件: wp-includes/ms-functions.php
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;
}
更新日志:

用戶貢獻的筆記:
(由Codex - 5年前貢獻)
例子:
//ADD USER ID 1 TO BLOG ID 1 AS AN EDITOR
$user_id = 1;
$blog_id = 1;
$role = 'editor';
add_user_to_blog( $blog_id, $user_id, $role )
?>
//ADD USER ID 2 TO BLOG ID 3 AS AN ADMINISTRATOR
$user_id = 2;
$blog_id = 3;
$role = 'administrator';
add_user_to_blog( $blog_id, $user_id, $role )
?>