add_user_to_blog

函数
add_user_to_blog ( $blog_id, $user_id, $role )
参数
  • (int) $blog_id ID of the blog the user is being added to.
    Required:
  • (int) $user_id ID of the user being added.
    Required:
  • (string) $role The role you want the user to have.
    Required:
返回值
  • (true|WP_Error) True on success or a WP_Error object if the user doesn't exist or could not be added.
定义位置
相关方法
add_new_user_to_blogadd_existing_user_to_blogget_users_of_blogadd_user_metamaybe_add_existing_user_to_blog
引入
-
弃用
-

add_user_to_blog – 将一个用户添加到WordPress的多站点网络中。它需要三个参数:要添加的用户的ID,要添加用户的站点的ID,以及用户在该站点的角色。

为博客添加一个用户,同时指定该用户的角色。

使用{@see ‘add_user_to_blog’}动作,在用户被添加到博客时触发一个事件。

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;
}

常见问题

FAQs
查看更多 >