bp_blogs_add_user_to_blog( int $user_id, string|bool $role = false, int $blog_id )
Record a user’s association with a blog.
Description
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.
Parameters
- $user_id
-
(Required) The ID of the user.
- $role
-
(Optional) User's WordPress role for this blog ID.
Default value: false
- $blog_id
-
(Required) Blog ID user is being added to.
Return
(false|null) False on failure.
Source
File: bp-blogs/bp-blogs-functions.php
function bp_blogs_add_user_to_blog( $user_id, $role = false, $blog_id = 0 ) { global $wpdb; // If no blog ID was passed, use the root blog ID. if ( empty( $blog_id ) ) { $blog_id = isset( $wpdb->blogid ) ? $wpdb->blogid : bp_get_root_blog_id(); } // If no role was passed, try to find the blog role. if ( empty( $role ) ) { // Get user capabilities. $key = $wpdb->get_blog_prefix( $blog_id ). 'capabilities'; $user_roles = array_keys( (array) bp_get_user_meta( $user_id, $key, true ) ); // User has roles so lets. if ( ! empty( $user_roles ) ) { // Get blog roles. $blog_roles = array_keys( bp_get_current_blog_roles() ); // Look for blog only roles of the user. $intersect_roles = array_intersect( $user_roles, $blog_roles ); // If there's a role in the array, use the first one. This isn't // very smart, but since roles aren't exactly hierarchical, and // WordPress does not yet have a UI for multiple user roles, it's // fine for now. if ( ! empty( $intersect_roles ) ) { $role = array_shift( $intersect_roles ); } } } // Bail if no role was found or role is not in the allowed roles array. if ( empty( $role ) || ! in_array( $role, bp_blogs_get_allowed_roles() ) ) { return false; } // Record the blog activity for this user being added to this blog. bp_blogs_record_blog( $blog_id, $user_id, true ); }
Questions?
We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.