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

Adds a user to a blog.


Description Description

Use the ‘add_user_to_blog’ action to fire an event when users are added to a blog.


Parameters Parameters

$blog_id

(int) (Required) ID of the blog you're adding the user to.

$user_id

(int) (Required) ID of the user you're adding.

$role

(string) (Required) The role you want the user to have


Top ↑

Return Return

(true|WP_Error)


Top ↑

Source Source

File: 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.' ) );
	}

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

Top ↑

Changelog Changelog

Changelog
Version Description
MU 1.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Codex

    Example

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

You must log in before being able to contribute a note or feedback.