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

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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

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.