BP_REST_Friends_Endpoint::create_item( WP_REST_Request $request )
Create a new friendship.
Description
Parameters
- $request
-
(Required) Full details about the request.
Return
(WP_REST_Response) | WP_Error
Source
File: bp-friends/classes/class-bp-rest-friends-endpoint.php
public function create_item( $request ) {
$request->set_param( 'context', 'edit' );
$initiator_id = get_user_by( 'id', $request['initiator_id'] );
$friend_id = get_user_by( 'id', $request['friend_id'] );
// Check if users are valid.
if ( ! $initiator_id || ! $friend_id ) {
return new WP_Error(
'bp_rest_friends_create_item_failed',
__( 'There was a problem confirming if user is a valid one.', 'buddyboss' ),
array(
'status' => 404,
)
);
}
// Check if users are friends or if there is a friendship request.
if ( 'not_friends' !== friends_check_friendship_status( $initiator_id->ID, $friend_id->ID ) ) {
return new WP_Error(
'bp_rest_friends_create_item_failed',
__( 'Those users are already friends or have sent friendship request(s) recently.', 'buddyboss' ),
array(
'status' => 500,
)
);
}
$is_moderator = bp_current_user_can( 'bp_moderate' );
// Only admins can create friendship requests for other people.
if ( ! in_array( bp_loggedin_user_id(), array( $initiator_id->ID, $friend_id->ID ), true ) && ! $is_moderator ) {
return new WP_Error(
'bp_rest_friends_create_item_failed',
__( 'You are not allowed to perform this action.', 'buddyboss' ),
array(
'status' => 403,
)
);
}
// Only admins can force a friendship request.
$force = false;
if ( true === $request->get_param( 'force' ) && $is_moderator ) {
$force = true;
}
// Adding friendship.
if ( ! friends_add_friend( $initiator_id->ID, $friend_id->ID, $request['force'] ) ) {
return new WP_Error(
'bp_rest_friends_create_item_failed',
__( 'There was an error trying to create the friendship.', 'buddyboss' ),
array(
'status' => 404,
)
);
}
// Get friendship.
$friendship = $this->get_friendship_object(
BP_Friends_Friendship::get_friendship_id( $initiator_id->ID, $friend_id->ID )
);
if ( ! $friendship || empty( $friendship->id ) ) {
return new WP_Error(
'bp_rest_invalid_id',
__( 'Friendship does not exist.', 'buddyboss' ),
array(
'status' => 404,
)
);
}
$retval = $this->prepare_response_for_collection(
$this->prepare_item_for_response( $friendship, $request )
);
$response = rest_ensure_response( $retval );
/**
* Fires after a friendship is created via the REST API.
*
* @param BP_Friends_Friendship $friendship The friendship object.
* @param WP_REST_Response $retval The response data.
* @param WP_REST_Request $request The request sent to the API.
*
* @since 0.1.0
*/
do_action( 'bp_rest_friends_create_item', $friendship, $response, $request );
return $response;
}
Changelog
| Version | Description |
|---|---|
| 0.1.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.