将用户添加到博客。

原型

add_user_to_blog( int $blog_id, int $user_id, string $role )

描述

将用户添加到博客时,使用“add_user_to_blog”操作触发事件。

参数

$blog_id (int) (Required) 你要添加用户的博客的ID。

$user_id (int) (Required) 你要添加的用户的ID。

$role (string) (Required) 你希望用户拥有的角色

返回值

(true|WP_Error)  

源文件

路径:wp-includes/ms-functions.php

<?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 bool|WP_Error $retval  True if the user should be added to the site, false
	 *                               or 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 );
	wp_cache_delete( $user_id, 'users' );
	wp_cache_delete( $blog_id . '_user_count', 'blog-details' );
	restore_current_blog();
	return true;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/add_user_to_blog/