bp_blogs_add_user_to_blog

Record a user's association with a blog.

Description

(bool|null) bp_blogs_add_user_to_blog( (int) $user_id, (constant) $role = false, (int) $blog_id = 0 ); 

This function is hooked to several WordPress actions where blog roles are set/changed ('add_user_to_blog', profile_update,, user_register). It parses the changes, and records them as necessary in the BP blog tracker.

BuddyPress does not track blogs for users with the subscriber role by default, though as of 2.1.0 you can filter bp_blogs_get_allowed_roles to modify this behavior.

Returns (bool|null)

False on failure.

Parameters (3)

0. $user_id (int)
The ID of the user.
1. $role — Optional. (constant) => false
User's WordPress role for this blog ID.
2. $blog_id — Optional. (int)
Blog ID user is being added to.

Usage

  1. if ( !function_exists( 'bp_blogs_add_user_to_blog' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'buddypress/bp-blogs/bp-blogs-functions.php'; 
  3.  
  4. // The ID of the user. 
  5. $user_id = -1; 
  6.  
  7. // User's WordPress role for this blog ID. 
  8. $role = false; 
  9.  
  10. // Blog ID user is being added to. 
  11. $blog_id = -1; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = bp_blogs_add_user_to_blog($user_id, $role, $blog_id); 
  15.  

Defined (1)

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

/bp-blogs/bp-blogs-functions.php  
  1. function bp_blogs_add_user_to_blog( $user_id, $role = false, $blog_id = 0 ) { 
  2. global $wpdb; 
  3.  
  4. // If no blog ID was passed, use the root blog ID. 
  5. if ( empty( $blog_id ) ) { 
  6. $blog_id = isset( $wpdb->blogid ) ? $wpdb->blogid : bp_get_root_blog_id(); 
  7.  
  8. // If no role was passed, try to find the blog role. 
  9. if ( empty( $role ) ) { 
  10.  
  11. // Get user capabilities. 
  12. $key = $wpdb->get_blog_prefix( $blog_id ). 'capabilities'; 
  13. $user_roles = array_keys( (array) bp_get_user_meta( $user_id, $key, true ) ); 
  14.  
  15. // User has roles so lets. 
  16. if ( ! empty( $user_roles ) ) { 
  17.  
  18. // Get blog roles. 
  19. $blog_roles = array_keys( bp_get_current_blog_roles() ); 
  20.  
  21. // Look for blog only roles of the user. 
  22. $intersect_roles = array_intersect( $user_roles, $blog_roles ); 
  23.  
  24. // If there's a role in the array, use the first one. This isn't 
  25. // very smart, but since roles aren't exactly hierarchical, and 
  26. // WordPress does not yet have a UI for multiple user roles, it's 
  27. // fine for now. 
  28. if ( ! empty( $intersect_roles ) ) { 
  29. $role = array_shift( $intersect_roles ); 
  30.  
  31. // Bail if no role was found or role is not in the allowed roles array. 
  32. if ( empty( $role ) || ! in_array( $role, bp_blogs_get_allowed_roles() ) ) { 
  33. return false; 
  34.  
  35. // Record the blog activity for this user being added to this blog. 
  36. bp_blogs_record_blog( $blog_id, $user_id, true );