Home › Forums › BP Better Messages › buddypress/v1/messages REST API › Reply To: buddypress/v1/messages REST API
March 9, 2023 at 11:11 pm
#19536
dennis
Participant
5. to add messages [POST] https://<yoursite>/?rest_route=/better-messages/v1/addmessagetothread&JWT=JWT
// register add message endpoint
add_action('rest_api_init', function () {
register_rest_route( 'better-messages/v1', '/addmessagetothread',array(
'methods' => 'POST',
'callback' => 'AddMessageToThread',
'permission_callback' => '__return_true'
));
});
// implementation
function AddMessageToThread($request) {
$user = wp_get_current_user();
// check if user is logged in >> return error
if ( $user->exists() == false) {
return new WP_Error( 'User is not logged in.', 'User is not logged in.', array('status' => 404) );
}
$sender_id = $user->ID;
$message_id = Better_Messages()->functions->new_message([
'sender_id' => $sender_id,
'thread_id' => $request['thread_id'],
'content' => $request['content'],
'return' => 'message_id',
]);
if ( is_wp_error( $message_id ) ) {
$error = $message_id->get_error_message();
return new WP_Error( 'Unable to post message to thread.' . $error, 'Unable to post message to thread.', array('status' => 404) );
} else {
$response = new WP_REST_Response($message_id);
$response->set_status(200);
return $response;
}
}