WP_REST_Comments_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error

In this article

Deletes a comment.

Parameters

$requestWP_REST_Requestrequired
Full details about the request.

Return

WP_REST_Response|WP_Error Response object on success, or error object on failure.

Source

public function delete_item( $request ) {
	$comment = $this->get_comment( $request['id'] );
	if ( is_wp_error( $comment ) ) {
		return $comment;
	}

	$force = isset( $request['force'] ) ? (bool) $request['force'] : false;

	/**
	 * Filters whether a comment can be trashed via the REST API.
	 *
	 * Return false to disable trash support for the comment.
	 *
	 * @since 4.7.0
	 *
	 * @param bool       $supports_trash Whether the comment supports trashing.
	 * @param WP_Comment $comment        The comment object being considered for trashing support.
	 */
	$supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );

	$request->set_param( 'context', 'edit' );

	if ( $force ) {
		$previous = $this->prepare_item_for_response( $comment, $request );
		$result   = wp_delete_comment( $comment->comment_ID, true );
		$response = new WP_REST_Response();
		$response->set_data(
			array(
				'deleted'  => true,
				'previous' => $previous->get_data(),
			)
		);
	} else {
		// If this type doesn't support trashing, error out.
		if ( ! $supports_trash ) {
			return new WP_Error(
				'rest_trash_not_supported',
				/* translators: %s: force=true */
				sprintf( __( "The comment does not support trashing. Set '%s' to delete." ), 'force=true' ),
				array( 'status' => 501 )
			);
		}

		if ( 'trash' === $comment->comment_approved ) {
			return new WP_Error(
				'rest_already_trashed',
				__( 'The comment has already been trashed.' ),
				array( 'status' => 410 )
			);
		}

		$result   = wp_trash_comment( $comment->comment_ID );
		$comment  = get_comment( $comment->comment_ID );
		$response = $this->prepare_item_for_response( $comment, $request );
	}

	if ( ! $result ) {
		return new WP_Error(
			'rest_cannot_delete',
			__( 'The comment cannot be deleted.' ),
			array( 'status' => 500 )
		);
	}

	/**
	 * Fires after a comment is deleted via the REST API.
	 *
	 * @since 4.7.0
	 *
	 * @param WP_Comment       $comment  The deleted comment data.
	 * @param WP_REST_Response $response The response returned from the API.
	 * @param WP_REST_Request  $request  The request sent to the API.
	 */
	do_action( 'rest_delete_comment', $comment, $response, $request );

	return $response;
}

Hooks

apply_filters( ‘rest_comment_trashable’, bool $supports_trash, WP_Comment $comment )

Filters whether a comment can be trashed via the REST API.

do_action( ‘rest_delete_comment’, WP_Comment $comment, WP_REST_Response $response, WP_REST_Request $request )

Fires after a comment is deleted via the REST API.

Changelog

VersionDescription
4.7.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.