add_user_to_blog()添加用户到博客(多站点)

目录

描述

Associates a user to a blog, along with specifying the user's role.

add_user_to_blog() 描述

用法

<?php add_user_to_blog$blog_id$user_id$role ?>

add_user_to_blog() 用法

参数

$blog_id

(integer) (必填) ID of the blog you're adding the user to.

默认值: None

$user_id

(integer) (必填) ID of the user you're adding.

默认值: None

$role

(string) (必填) The role you want the user to have

默认值: None

add_user_to_blog() 参数

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php
//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 )
?>

<?php 
//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 )
?>

add_user_to_blog() 示例

注意

  • 使用到 the 'add_user_to_blog' 动作 to fire an event when users are added to a blog.
  • It does not check if the user is already a member of the blog before setting their role. If you don't want to overwrite the role of a user if they are already a member of the blog, use is_user_member_of_blog() to check that first.
  • You do not need to call switch_to_blog() to switch to the blog you want to add the user to before calling this function. The function will switch to the blog itself, and restore the current blog before returning as well.

add_user_to_blog() 注意

源文件

add_user_to_blog() 函数的代码位于 wp-includes/ms-functions.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Add a user to a blog.
 *
 * Use the 'add_user_to_blog' action to fire an event when
 * users are added to a blog.
 *
 * @since MU 1.0
 *
 * @param int    $blog_id ID of the blog you're adding the user to.
 * @param int    $user_id ID of the user you're adding.
 * @param string $role    The role you want the user to have
 * @return true|WP_Error
 */
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.' ) );
	}

	if ( !get_user_meta($user_id, 'primary_blog', true) ) {
		update_user_meta($user_id, 'primary_blog', $blog_id);
		$details = get_blog_details($blog_id);
		update_user_meta($user_id, 'source_domain', $details->domain);
	}

	$user->set_role($role);

	/**
	 * Fires immediately after a user is added to a site.
	 *
	 * @since MU
	 *
	 * @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;
}

add_user_to_blog() 源文件

相关