BP_REST_Messages_Endpoint::create_item( WP_REST_Request $request )
Init a Messages Thread or add a reply to an existing Thread.
Description
Parameters
- $request
-
(Required) Full details about the request.
Return
(WP_REST_Response) | WP_Error
Source
File: bp-messages/classes/class-bp-rest-messages-endpoint.php
public function create_item( $request ) {
// Setting context.
$request->set_param( 'context', 'edit' );
if ( empty( $request['id'] ) && empty( $request['recipients'] ) ) {
return new WP_Error(
'bp_rest_empty_recipients',
__( 'Please, enter recipients user IDs.', 'buddyboss' ),
array(
'status' => 400,
)
);
}
$message_object = $this->prepare_item_for_database( $request );
// Create the message or the reply.
$thread_id = messages_new_message( $message_object );
// Validate it created a Thread or was added to it.
if ( false === $thread_id ) {
return new WP_Error(
'bp_rest_messages_create_failed',
__( 'There was an error trying to create the message.', 'buddyboss' ),
array(
'status' => 500,
)
);
}
global $bp, $wpdb;
// Mark thread active if it's in hidden mode.
$unread_query = $wpdb->prepare( "UPDATE {$bp->messages->table_name_recipients} SET is_hidden = %d WHERE thread_id = %d AND user_id = %d", 0, $thread_id, $message_object->sender_id ); // phpcs:ignore
$wpdb->query( $unread_query ); // phpcs:ignore
// Make sure to get the newest message to update REST Additional fields.
$thread = $this->get_thread_object( $thread_id );
$last_message = reset( $thread->messages );
$fields_update = $this->update_additional_fields_for_object( $last_message, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$retval = $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.
*
* @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.
*
* @since 0.1.0
*/
do_action( 'bp_rest_messages_create_item', $thread, $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.