Using WordPress ‘add_user_to_blog()’ PHP function

The add_user_to_blog() WordPress PHP function is used to add a user to a blog with a specified role. This function triggers an ‘add_user_to_blog’ event when a user is added to a blog.

Usage

Here’s an example of how the add_user_to_blog() function can be used:

// Assigning values
$blog_id = 2; 
$user_id = 4; 
$role = 'editor'; 

// Adding the user to the blog
add_user_to_blog($blog_id, $user_id, $role); 

In this example, the user with ID 4 is added to the blog with ID 2 as an editor.

Parameters

  • $blog_id (int): Required. The ID of the blog to which the user is being added.
  • $user_id (int): Required. The ID of the user being added.
  • $role (string): Required. The role assigned to the user in the blog.

More information

See WordPress Developer Resources: add_user_to_blog()
This function was implemented in WordPress version 3.0.0.

Examples

Adding a User as an Editor

$blog_id = 1; 
$user_id = 1; 
$role = 'editor'; 
add_user_to_blog($blog_id, $user_id, $role); 

This code adds the user with ID 1 to the blog with ID 1 as an editor.

Adding a User as an Administrator

$blog_id = 3; 
$user_id = 2; 
$role = 'administrator'; 
add_user_to_blog($blog_id, $user_id, $role); 

This code adds the user with ID 2 to the blog with ID 3 as an administrator.

Adding Multiple Users to a Blog

$blog_id = 1; 
$user_ids = array(1, 2, 3); 
$role = 'author'; 

foreach ($user_ids as $user_id) {
    add_user_to_blog($blog_id, $user_id, $role);
}

This code adds users with IDs 1, 2, and 3 to the blog with ID 1 as authors.

Adding a User to Multiple Blogs

$user_id = 1; 
$blog_ids = array(1, 2, 3); 
$role = 'editor'; 

foreach ($blog_ids as $blog_id) {
    add_user_to_blog($blog_id, $user_id, $role);
}

This code adds the user with ID 1 as an editor to blogs with IDs 1, 2, and 3.

Changing a User’s Role

$blog_id = 1; 
$user_id = 1; 
$role = 'administrator'; 
add_user_to_blog($blog_id, $user_id, $role);

This code changes the user with ID 1 role to administrator in the blog with ID 1.