diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php index fbe5259334..d7a34f3301 100644 --- a/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php +++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php @@ -552,13 +552,19 @@ class WP_REST_Comments_Controller extends WP_REST_Controller { * Filters a comment before it is inserted via the REST API. * * Allows modification of the comment right before it is inserted via wp_insert_comment(). + * Returning a WP_Error value from the filter will shortcircuit insertion and allow + * skipping further processing. * * @since 4.7.0 + * @since 4.8.0 $prepared_comment can now be a WP_Error to shortcircuit insertion. * - * @param array $prepared_comment The prepared comment data for wp_insert_comment(). + * @param array|WP_Error $prepared_comment The prepared comment data for wp_insert_comment(). * @param WP_REST_Request $request Request used to insert the comment. */ $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request ); + if ( is_wp_error( $prepared_comment ) ) { + return $prepared_comment; + } $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) ); diff --git a/tests/phpunit/tests/rest-api/rest-comments-controller.php b/tests/phpunit/tests/rest-api/rest-comments-controller.php index 99de8bd110..29fe144458 100644 --- a/tests/phpunit/tests/rest-api/rest-comments-controller.php +++ b/tests/phpunit/tests/rest-api/rest-comments-controller.php @@ -985,6 +985,32 @@ class WP_Test_REST_Comments_Controller extends WP_Test_REST_Controller_Testcase $this->assertEquals( $params['content']['raw'], $new_comment->comment_content ); } + public function test_create_item_error_from_filter() { + add_filter( 'rest_pre_insert_comment', array( $this, 'return_premade_error' ) ); + wp_set_current_user( self::$admin_id ); + + $params = array( + 'post' => self::$post_id, + 'author_name' => 'Homer Jay Simpson', + 'author_email' => 'homer@example.org', + 'content' => array( + 'raw' => 'Aw, he loves beer. Here, little fella.' + ), + ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/comments' ); + $request->add_header( 'content-type', 'application/json' ); + $request->set_body( wp_json_encode( $params ) ); + + $response = $this->server->dispatch( $request ); + + $this->assertErrorResponse( 'test_rest_premade_error', $response, 418 ); + } + + public function return_premade_error() { + return new WP_Error( 'test_rest_premade_error', "I'm sorry, I thought he was a party robot.", array( 'status' => 418 ) ); + } + public function test_create_comment_missing_required_author_name() { add_filter( 'rest_allow_anonymous_comments', '__return_true' ); update_option( 'require_name_email', 1 );