friends_add_friend( int $initiator_userid, int $friend_userid, bool $force_accept = false )

Create a new friendship.


Parameters Parameters

$initiator_userid

(int) (Required) ID of the "initiator" user (the user who is sending the friendship request).

$friend_userid

(int) (Required) ID of the "friend" user (the user whose friendship is being requested).

$force_accept

(bool) (Optional) Whether to force acceptance. When false, running friends_add_friend() will result in a friendship request. When true, running friends_add_friend() will result in an accepted friendship, with no notifications being sent. Default: false.

Default value: false


Top ↑

Return Return

(bool) True on success, false on failure.


Source Source

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

function friends_add_friend( $initiator_userid, $friend_userid, $force_accept = false ) {

	// You cannot be friends with yourself!
	if ( $initiator_userid == $friend_userid ) {
		return false;
	}

	// Check if already friends, and bail if so.
	if ( friends_check_friendship( $initiator_userid, $friend_userid ) ) {
		return true;
	}

	// Setup the friendship data.
	$friendship = new BP_Friends_Friendship;
	$friendship->initiator_user_id = (int) $initiator_userid;
	$friendship->friend_user_id    = (int) $friend_userid;
	$friendship->is_confirmed      = 0;
	$friendship->is_limited        = 0;
	$friendship->date_created      = bp_core_current_time();

	if ( ! empty( $force_accept ) ) {
		$friendship->is_confirmed = 1;
	}

	// Bail if friendship could not be saved (how sad!).
	if ( ! $friendship->save() ) {
		return false;
	}

	// Send notifications.
	if ( empty( $force_accept ) ) {
		$action = 'requested';

	// Update friend totals.
	} else {
		$action = 'accepted';
		friends_update_friend_totals( $friendship->initiator_user_id, $friendship->friend_user_id, 'add' );
	}

	/**
	 * Fires at the end of initiating a new friendship connection.
	 *
	 * This is a variable hook, depending on context.
	 * The two potential hooks are: friends_friendship_requested, friends_friendship_accepted.
	 *
	 * @since 1.0.0
	 *
	 * @param int    $id                ID of the pending friendship connection.
	 * @param int    $initiator_user_id ID of the friendship initiator.
	 * @param int    $friend_user_id    ID of the friend user.
	 * @param object $friendship        BuddyPress Friendship Object.
	 */
	do_action( 'friends_friendship_' . $action, $friendship->id, $friendship->initiator_user_id, $friendship->friend_user_id, $friendship );

	return true;
}


Top ↑

Changelog Changelog

Changelog
Version Description
1.0.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

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