BP_REST_Messages_Endpoint::create_item( WP_REST_Request $request )
Init a Messages Thread or add a reply to an existing Thread.
Description Description
Parameters Parameters
- $request
-
(Required) Full details about the request.
Return Return
(WP_REST_Response|WP_Error)
Source Source
File: bp-messages/classes/class-bp-rest-messages-endpoint.php
public function create_item( $request ) {
// Setting context.
$request->set_param( 'context', 'edit' );
// Prepare the message or the reply arguments.
$args = array(
'sender_id' => $request['sender_id'],
'thread_id' => 0,
'subject' => $request['subject'],
'content' => $request['message'],
'recipients' => $request['recipients'],
);
$error = new WP_Error(
'bp_rest_messages_create_failed',
__( 'There was an error trying to create the message.', 'buddypress' ),
array(
'status' => 500,
)
);
// Replying to an existing Thread ?
if ( $request['id'] ) {
// Try to get the thread.
$thread = $this->get_thread_object( $request['id'] );
// Validate the Thread exists.
if ( ! $thread->thread_id ) {
return $error;
}
$args['thread_id'] = (int) $thread->thread_id;
$args['recipients'] = wp_parse_id_list( wp_list_pluck( $thread->recipients, 'user_id' ) );
}
if ( ! $args['recipients'] ) {
return new WP_Error(
'bp_rest_messages_missing_recipients',
__( 'Please provide some recipients for your message or reply.', 'buddypress' ),
array(
'status' => 400,
)
);
}
// Create the message or the reply.
$thread_id = messages_new_message( $args );
// Validate it created a Thread or was added to it.
if ( ! $thread_id ) {
return $error;
}
// Make sure to get the newest message to update REST Additional fields.
$thread = $this->get_thread_object( $thread_id );
$last_message = wp_list_filter( $thread->messages, array( 'id' => $thread->last_message_id ) );
$last_message = reset( $last_message );
$fields_update = $this->update_additional_fields_for_object( $last_message, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$retval = array(
$this->prepare_response_for_collection(
$this->prepare_item_for_response( $thread, $request )
),
);
$response = rest_ensure_response( $retval );
/**
* Fires after a message is created via the REST API.
*
* @since 5.0.0
*
* @param BP_Messages_Thread $thread Thread object.
* @param WP_REST_Response $retval The response data.
* @param WP_REST_Request $request The request sent to the API.
*/
do_action( 'bp_rest_messages_create_item', $thread, $response, $request );
return $response;
}
Changelog Changelog
| Version | Description |
|---|---|
| 5.0.0 | Introduced. |