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 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.


Top ↑

Parameters Parameters

$user_id

(int) (Required) The ID of the user.

$role

(string|bool) (Optional) User's WordPress role for this blog ID.

Default value: false

$blog_id

(int) (Required) Blog ID user is being added to.


Top ↑

Return Return

(false|null) False on failure.


Source 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 );
}


Top ↑

User Contributed Notes User Contributed Notes

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