diff --git a/lib/endpoints/class-wp-rest-comments-controller.php b/lib/endpoints/class-wp-rest-comments-controller.php index 4c7f671967..3605d2acef 100644 --- a/lib/endpoints/class-wp-rest-comments-controller.php +++ b/lib/endpoints/class-wp-rest-comments-controller.php @@ -158,6 +158,21 @@ public function create_item( $request ) { if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) { $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true ); } + + // Set author data if the user's logged in + $missing_author = empty( $prepared_comment['user_id'] ) + && empty( $prepared_comment['comment_author'] ) + && empty( $prepared_comment['comment_author_email'] ) + && empty( $prepared_comment['comment_author_url'] ); + + if ( is_user_logged_in() && $missing_author ) { + $user = wp_get_current_user(); + $prepared_comment['user_id'] = $user->ID; + $prepared_comment['comment_author'] = $user->display_name; + $prepared_comment['comment_author_email'] = $user->user_email; + $prepared_comment['comment_author_url'] = $user->user_url; + } + if ( ! isset( $prepared_comment['comment_author_email'] ) ) { $prepared_comment['comment_author_email'] = ''; } diff --git a/tests/test-rest-comments-controller.php b/tests/test-rest-comments-controller.php index 1b632d1086..133c42c2ae 100644 --- a/tests/test-rest-comments-controller.php +++ b/tests/test-rest-comments-controller.php @@ -386,6 +386,32 @@ public function test_create_item_assign_different_user() { $this->assertEquals( $this->subscriber_id, $data['author'] ); } + public function test_create_item_current_user() { + wp_set_current_user( $this->subscriber_id ); + + $params = array( + 'post' => $this->post_id, + 'content' => "Well sir, there's nothing on earth like a genuine, bona fide, electrified, six-car Monorail!", + ); + + $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 ); + + $response = rest_ensure_response( $response ); + $this->assertEquals( 201, $response->get_status() ); + $data = $response->get_data(); + $this->assertEquals( $this->subscriber_id, $data['author'] ); + + // Check author data matches + $author = get_user_by( 'id', $this->subscriber_id ); + $comment = get_comment( $data['id'] ); + $this->assertEquals( $author->display_name, $comment->comment_author ); + $this->assertEquals( $author->user_email, $comment->comment_author_email ); + $this->assertEquals( $author->user_url, $comment->comment_author_url ); + } + public function test_create_comment_other_user() { wp_set_current_user( $this->admin_id );