groups_join_group( int $group_id, int $user_id )

Add a user to a group.

Description

Parameters

$group_id

(int) (Required) ID of the group.

$user_id

(int) (Optional) ID of the user. Defaults to the currently logged-in user.

Return

(bool) True on success, false on failure.

Source

File: bp-groups/bp-groups-functions.php

function groups_join_group( $group_id, $user_id = 0 ) {

	if ( empty( $user_id ) )
		$user_id = bp_loggedin_user_id();

	// Check if the user has an outstanding invite. If so, delete it.
	if ( groups_check_user_has_invite( $user_id, $group_id ) )
		groups_delete_invite( $user_id, $group_id );

	// Check if the user has an outstanding request. If so, delete it.
	if ( groups_check_for_membership_request( $user_id, $group_id ) )
		groups_delete_membership_request( null, $user_id, $group_id );

	// User is already a member, just return true.
	if ( groups_is_user_member( $user_id, $group_id ) )
		return true;

	$new_member                = new BP_Groups_Member;
	$new_member->group_id      = $group_id;
	$new_member->user_id       = $user_id;
	$new_member->inviter_id    = 0;
	$new_member->is_admin      = 0;
	$new_member->user_title    = '';
	$new_member->date_modified = bp_core_current_time();
	$new_member->is_confirmed  = 1;

	if ( !$new_member->save() )
		return false;

	$bp = buddypress();

	if ( !isset( $bp->groups->current_group ) || !$bp->groups->current_group || $group_id != $bp->groups->current_group->id )
		$group = groups_get_group( $group_id );
	else
		$group = $bp->groups->current_group;

	// Record this in activity feeds.
	if ( bp_is_active( 'activity' ) ) {
		groups_record_activity( array(
			'type'    => 'joined_group',
			'item_id' => $group_id,
			'user_id' => $user_id,
		) );
	}

	/**
	 * Fires after a user joins a group.
	 *
	 * @since BuddyPress 1.0.0
	 *
	 * @param int $group_id ID of the group.
	 * @param int $user_id  ID of the user joining the group.
	 */
	do_action( 'groups_join_group', $group_id, $user_id );

	return true;
}

Changelog

Changelog
Version Description
BuddyPress 1.0.0 Introduced.

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.