add_user_to_blog

Adds a user to a blog.

Description

(true|WP_Error) add_user_to_blog( (int) $blog_id, (int) $user_id, (string) $role ); 

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

Returns (true|WP_Error)

Parameters (3)

0. $blog_id (int)
ID of the blog you're adding the user to.
1. $user_id (int)
ID of the user you're adding.
2. $role (string)
The role you want the user to have

Usage

  1. if ( !function_exists( 'add_user_to_blog' ) ) { 
  2. require_once ABSPATH . WPINC . '/ms-functions.php'; 
  3.  
  4. // ID of the blog you're adding the user to. 
  5. $blog_id = -1; 
  6.  
  7. // ID of the user you're adding. 
  8. $user_id = -1; 
  9.  
  10. // The role you want the user to have 
  11. $role = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = add_user_to_blog($blog_id, $user_id, $role); 
  15.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/ms-functions.php  
  1. function add_user_to_blog( $blog_id, $user_id, $role ) { 
  2. switch_to_blog($blog_id); 
  3.  
  4. $user = get_userdata( $user_id ); 
  5.  
  6. if ( ! $user ) { 
  7. return new WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) ); 
  8.  
  9. if ( !get_user_meta($user_id, 'primary_blog', true) ) { 
  10. update_user_meta($user_id, 'primary_blog', $blog_id); 
  11. $details = get_blog_details($blog_id); 
  12. update_user_meta($user_id, 'source_domain', $details->domain); 
  13.  
  14. $user->set_role($role); 
  15.  
  16. /** 
  17. * Fires immediately after a user is added to a site. 
  18. * @since MU 
  19. * @param int $user_id User ID. 
  20. * @param string $role User role. 
  21. * @param int $blog_id Blog ID. 
  22. */ 
  23. do_action( 'add_user_to_blog', $user_id, $role, $blog_id ); 
  24. wp_cache_delete( $user_id, 'users' ); 
  25. wp_cache_delete( $blog_id . '_user_count', 'blog-details' ); 
  26. return true;