3 * REST API: WP_REST_Comments_Controller class
11 * Core controller used to access comments via the REST API.
15 * @see WP_REST_Controller
17 class WP_REST_Comments_Controller extends WP_REST_Controller {
20 * Instance of a comment meta fields object.
24 * @var WP_REST_Comment_Meta_Fields
34 public function __construct() {
35 $this->namespace = 'wp/v2';
36 $this->rest_base = 'comments';
38 $this->meta = new WP_REST_Comment_Meta_Fields();
42 * Registers the routes for the objects of the controller.
47 public function register_routes() {
49 register_rest_route( $this->namespace, '/' . $this->rest_base, array(
51 'methods' => WP_REST_Server::READABLE,
52 'callback' => array( $this, 'get_items' ),
53 'permission_callback' => array( $this, 'get_items_permissions_check' ),
54 'args' => $this->get_collection_params(),
57 'methods' => WP_REST_Server::CREATABLE,
58 'callback' => array( $this, 'create_item' ),
59 'permission_callback' => array( $this, 'create_item_permissions_check' ),
60 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
62 'schema' => array( $this, 'get_public_item_schema' ),
65 register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
68 'description' => __( 'Unique identifier for the object.' ),
73 'methods' => WP_REST_Server::READABLE,
74 'callback' => array( $this, 'get_item' ),
75 'permission_callback' => array( $this, 'get_item_permissions_check' ),
77 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
79 'description' => __( 'The password for the post if it is password protected.' ),
85 'methods' => WP_REST_Server::EDITABLE,
86 'callback' => array( $this, 'update_item' ),
87 'permission_callback' => array( $this, 'update_item_permissions_check' ),
88 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
91 'methods' => WP_REST_Server::DELETABLE,
92 'callback' => array( $this, 'delete_item' ),
93 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
98 'description' => __( 'Whether to bypass trash and force deletion.' ),
101 'description' => __( 'The password for the post if it is password protected.' ),
106 'schema' => array( $this, 'get_public_item_schema' ),
111 * Checks if a given request has access to read comments.
116 * @param WP_REST_Request $request Full details about the request.
117 * @return WP_Error|bool True if the request has read access, error object otherwise.
119 public function get_items_permissions_check( $request ) {
121 if ( ! empty( $request['post'] ) ) {
122 foreach ( (array) $request['post'] as $post_id ) {
123 $post = get_post( $post_id );
125 if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post, $request ) ) {
126 return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
127 } elseif ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) {
128 return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read comments without a post.' ), array( 'status' => rest_authorization_required_code() ) );
133 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
134 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
137 if ( ! current_user_can( 'edit_posts' ) ) {
138 $protected_params = array( 'author', 'author_exclude', 'author_email', 'type', 'status' );
139 $forbidden_params = array();
141 foreach ( $protected_params as $param ) {
142 if ( 'status' === $param ) {
143 if ( 'approve' !== $request[ $param ] ) {
144 $forbidden_params[] = $param;
146 } elseif ( 'type' === $param ) {
147 if ( 'comment' !== $request[ $param ] ) {
148 $forbidden_params[] = $param;
150 } elseif ( ! empty( $request[ $param ] ) ) {
151 $forbidden_params[] = $param;
155 if ( ! empty( $forbidden_params ) ) {
156 return new WP_Error( 'rest_forbidden_param', sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ), array( 'status' => rest_authorization_required_code() ) );
164 * Retrieves a list of comment items.
169 * @param WP_REST_Request $request Full details about the request.
170 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
172 public function get_items( $request ) {
174 // Retrieve the list of registered collection query parameters.
175 $registered = $this->get_collection_params();
178 * This array defines mappings between public API query parameters whose
179 * values are accepted as-passed, and their internal WP_Query parameter
180 * name equivalents (some are the same). Only values which are also
181 * present in $registered will be set.
183 $parameter_mappings = array(
184 'author' => 'author__in',
185 'author_email' => 'author_email',
186 'author_exclude' => 'author__not_in',
187 'exclude' => 'comment__not_in',
188 'include' => 'comment__in',
189 'offset' => 'offset',
191 'parent' => 'parent__in',
192 'parent_exclude' => 'parent__not_in',
193 'per_page' => 'number',
194 'post' => 'post__in',
195 'search' => 'search',
196 'status' => 'status',
200 $prepared_args = array();
203 * For each known parameter which is both registered and present in the request,
204 * set the parameter's value on the query $prepared_args.
206 foreach ( $parameter_mappings as $api_param => $wp_param ) {
207 if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
208 $prepared_args[ $wp_param ] = $request[ $api_param ];
212 // Ensure certain parameter values default to empty strings.
213 foreach ( array( 'author_email', 'search' ) as $param ) {
214 if ( ! isset( $prepared_args[ $param ] ) ) {
215 $prepared_args[ $param ] = '';
219 if ( isset( $registered['orderby'] ) ) {
220 $prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] );
223 $prepared_args['no_found_rows'] = false;
225 $prepared_args['date_query'] = array();
227 // Set before into date query. Date query must be specified as an array of an array.
228 if ( isset( $registered['before'], $request['before'] ) ) {
229 $prepared_args['date_query'][0]['before'] = $request['before'];
232 // Set after into date query. Date query must be specified as an array of an array.
233 if ( isset( $registered['after'], $request['after'] ) ) {
234 $prepared_args['date_query'][0]['after'] = $request['after'];
237 if ( isset( $registered['page'] ) && empty( $request['offset'] ) ) {
238 $prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 );
242 * Filters arguments, before passing to WP_Comment_Query, when querying comments via the REST API.
246 * @link https://developer.wordpress.org/reference/classes/wp_comment_query/
248 * @param array $prepared_args Array of arguments for WP_Comment_Query.
249 * @param WP_REST_Request $request The current request.
251 $prepared_args = apply_filters( 'rest_comment_query', $prepared_args, $request );
253 $query = new WP_Comment_Query;
254 $query_result = $query->query( $prepared_args );
258 foreach ( $query_result as $comment ) {
259 if ( ! $this->check_read_permission( $comment, $request ) ) {
263 $data = $this->prepare_item_for_response( $comment, $request );
264 $comments[] = $this->prepare_response_for_collection( $data );
267 $total_comments = (int) $query->found_comments;
268 $max_pages = (int) $query->max_num_pages;
270 if ( $total_comments < 1 ) {
271 // Out-of-bounds, run the query again without LIMIT for total count.
272 unset( $prepared_args['number'], $prepared_args['offset'] );
274 $query = new WP_Comment_Query;
275 $prepared_args['count'] = true;
277 $total_comments = $query->query( $prepared_args );
278 $max_pages = ceil( $total_comments / $request['per_page'] );
281 $response = rest_ensure_response( $comments );
282 $response->header( 'X-WP-Total', $total_comments );
283 $response->header( 'X-WP-TotalPages', $max_pages );
285 $base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
287 if ( $request['page'] > 1 ) {
288 $prev_page = $request['page'] - 1;
290 if ( $prev_page > $max_pages ) {
291 $prev_page = $max_pages;
294 $prev_link = add_query_arg( 'page', $prev_page, $base );
295 $response->link_header( 'prev', $prev_link );
298 if ( $max_pages > $request['page'] ) {
299 $next_page = $request['page'] + 1;
300 $next_link = add_query_arg( 'page', $next_page, $base );
302 $response->link_header( 'next', $next_link );
309 * Get the comment, if the ID is valid.
313 * @param int $id Supplied ID.
314 * @return WP_Comment|WP_Error Comment object if ID is valid, WP_Error otherwise.
316 protected function get_comment( $id ) {
317 $error = new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
318 if ( (int) $id <= 0 ) {
323 $comment = get_comment( $id );
324 if ( empty( $comment ) ) {
328 if ( ! empty( $comment->comment_post_ID ) ) {
329 $post = get_post( (int) $comment->comment_post_ID );
330 if ( empty( $post ) ) {
331 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
339 * Checks if a given request has access to read the comment.
344 * @param WP_REST_Request $request Full details about the request.
345 * @return WP_Error|bool True if the request has read access for the item, error object otherwise.
347 public function get_item_permissions_check( $request ) {
348 $comment = $this->get_comment( $request['id'] );
349 if ( is_wp_error( $comment ) ) {
353 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
354 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
357 $post = get_post( $comment->comment_post_ID );
359 if ( ! $this->check_read_permission( $comment, $request ) ) {
360 return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read this comment.' ), array( 'status' => rest_authorization_required_code() ) );
363 if ( $post && ! $this->check_read_post_permission( $post, $request ) ) {
364 return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
371 * Retrieves a comment.
376 * @param WP_REST_Request $request Full details about the request.
377 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
379 public function get_item( $request ) {
380 $comment = $this->get_comment( $request['id'] );
381 if ( is_wp_error( $comment ) ) {
385 $data = $this->prepare_item_for_response( $comment, $request );
386 $response = rest_ensure_response( $data );
392 * Checks if a given request has access to create a comment.
397 * @param WP_REST_Request $request Full details about the request.
398 * @return WP_Error|bool True if the request has access to create items, error object otherwise.
400 public function create_item_permissions_check( $request ) {
401 if ( ! is_user_logged_in() ) {
402 if ( get_option( 'comment_registration' ) ) {
403 return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
407 * Filter whether comments can be created without authentication.
409 * Enables creating comments for anonymous users.
413 * @param bool $allow_anonymous Whether to allow anonymous comments to
414 * be created. Default `false`.
415 * @param WP_REST_Request $request Request used to generate the
418 $allow_anonymous = apply_filters( 'rest_allow_anonymous_comments', false, $request );
419 if ( ! $allow_anonymous ) {
420 return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
424 // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default.
425 if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) {
426 return new WP_Error( 'rest_comment_invalid_author',
427 /* translators: %s: request parameter */
428 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ),
429 array( 'status' => rest_authorization_required_code() )
433 if ( isset( $request['author_ip'] ) && ! current_user_can( 'moderate_comments' ) ) {
434 if ( empty( $_SERVER['REMOTE_ADDR'] ) || $request['author_ip'] !== $_SERVER['REMOTE_ADDR'] ) {
435 return new WP_Error( 'rest_comment_invalid_author_ip',
436 /* translators: %s: request parameter */
437 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author_ip' ),
438 array( 'status' => rest_authorization_required_code() )
443 if ( isset( $request['status'] ) && ! current_user_can( 'moderate_comments' ) ) {
444 return new WP_Error( 'rest_comment_invalid_status',
445 /* translators: %s: request parameter */
446 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'status' ),
447 array( 'status' => rest_authorization_required_code() )
451 if ( empty( $request['post'] ) ) {
452 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
455 $post = get_post( (int) $request['post'] );
457 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
460 if ( 'draft' === $post->post_status ) {
461 return new WP_Error( 'rest_comment_draft_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
464 if ( 'trash' === $post->post_status ) {
465 return new WP_Error( 'rest_comment_trash_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
468 if ( ! $this->check_read_post_permission( $post, $request ) ) {
469 return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) );
472 if ( ! comments_open( $post->ID ) ) {
473 return new WP_Error( 'rest_comment_closed', __( 'Sorry, comments are closed for this item.' ), array( 'status' => 403 ) );
485 * @param WP_REST_Request $request Full details about the request.
486 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
488 public function create_item( $request ) {
489 if ( ! empty( $request['id'] ) ) {
490 return new WP_Error( 'rest_comment_exists', __( 'Cannot create existing comment.' ), array( 'status' => 400 ) );
493 // Do not allow comments to be created with a non-default type.
494 if ( ! empty( $request['type'] ) && 'comment' !== $request['type'] ) {
495 return new WP_Error( 'rest_invalid_comment_type', __( 'Cannot create a comment with that type.' ), array( 'status' => 400 ) );
498 $prepared_comment = $this->prepare_item_for_database( $request );
499 if ( is_wp_error( $prepared_comment ) ) {
500 return $prepared_comment;
503 $prepared_comment['comment_type'] = '';
506 * Do not allow a comment to be created with missing or empty
507 * comment_content. See wp_handle_comment_submission().
509 if ( empty( $prepared_comment['comment_content'] ) ) {
510 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
513 // Setting remaining values before wp_insert_comment so we can use wp_allow_comment().
514 if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) {
515 $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true );
518 // Set author data if the user's logged in.
519 $missing_author = empty( $prepared_comment['user_id'] )
520 && empty( $prepared_comment['comment_author'] )
521 && empty( $prepared_comment['comment_author_email'] )
522 && empty( $prepared_comment['comment_author_url'] );
524 if ( is_user_logged_in() && $missing_author ) {
525 $user = wp_get_current_user();
527 $prepared_comment['user_id'] = $user->ID;
528 $prepared_comment['comment_author'] = $user->display_name;
529 $prepared_comment['comment_author_email'] = $user->user_email;
530 $prepared_comment['comment_author_url'] = $user->user_url;
533 // Honor the discussion setting that requires a name and email address of the comment author.
534 if ( get_option( 'require_name_email' ) ) {
535 if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) {
536 return new WP_Error( 'rest_comment_author_data_required', __( 'Creating a comment requires valid author name and email values.' ), array( 'status' => 400 ) );
540 if ( ! isset( $prepared_comment['comment_author_email'] ) ) {
541 $prepared_comment['comment_author_email'] = '';
544 if ( ! isset( $prepared_comment['comment_author_url'] ) ) {
545 $prepared_comment['comment_author_url'] = '';
548 if ( ! isset( $prepared_comment['comment_agent'] ) ) {
549 $prepared_comment['comment_agent'] = '';
552 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment );
553 if ( is_wp_error( $check_comment_lengths ) ) {
554 $error_code = $check_comment_lengths->get_error_code();
555 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
558 $prepared_comment['comment_approved'] = wp_allow_comment( $prepared_comment, true );
560 if ( is_wp_error( $prepared_comment['comment_approved'] ) ) {
561 $error_code = $prepared_comment['comment_approved']->get_error_code();
562 $error_message = $prepared_comment['comment_approved']->get_error_message();
564 if ( 'comment_duplicate' === $error_code ) {
565 return new WP_Error( $error_code, $error_message, array( 'status' => 409 ) );
568 if ( 'comment_flood' === $error_code ) {
569 return new WP_Error( $error_code, $error_message, array( 'status' => 400 ) );
572 return $prepared_comment['comment_approved'];
576 * Filters a comment before it is inserted via the REST API.
578 * Allows modification of the comment right before it is inserted via wp_insert_comment().
582 * @param array $prepared_comment The prepared comment data for wp_insert_comment().
583 * @param WP_REST_Request $request Request used to insert the comment.
585 $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request );
587 $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) );
589 if ( ! $comment_id ) {
590 return new WP_Error( 'rest_comment_failed_create', __( 'Creating comment failed.' ), array( 'status' => 500 ) );
593 if ( isset( $request['status'] ) ) {
594 $this->handle_status_param( $request['status'], $comment_id );
597 $comment = get_comment( $comment_id );
600 * Fires after a comment is created or updated via the REST API.
604 * @param WP_Comment $comment Inserted or updated comment object.
605 * @param WP_REST_Request $request Request object.
606 * @param bool $creating True when creating a comment, false
609 do_action( 'rest_insert_comment', $comment, $request, true );
611 $schema = $this->get_item_schema();
613 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
614 $meta_update = $this->meta->update_value( $request['meta'], $comment_id );
616 if ( is_wp_error( $meta_update ) ) {
621 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
623 if ( is_wp_error( $fields_update ) ) {
624 return $fields_update;
627 $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view';
629 $request->set_param( 'context', $context );
631 $response = $this->prepare_item_for_response( $comment, $request );
632 $response = rest_ensure_response( $response );
634 $response->set_status( 201 );
635 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) );
642 * Checks if a given REST request has access to update a comment.
647 * @param WP_REST_Request $request Full details about the request.
648 * @return WP_Error|bool True if the request has access to update the item, error object otherwise.
650 public function update_item_permissions_check( $request ) {
651 $comment = $this->get_comment( $request['id'] );
652 if ( is_wp_error( $comment ) ) {
656 if ( ! $this->check_edit_permission( $comment ) ) {
657 return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this comment.' ), array( 'status' => rest_authorization_required_code() ) );
669 * @param WP_REST_Request $request Full details about the request.
670 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
672 public function update_item( $request ) {
673 $comment = $this->get_comment( $request['id'] );
674 if ( is_wp_error( $comment ) ) {
678 $id = $comment->comment_ID;
680 if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) {
681 return new WP_Error( 'rest_comment_invalid_type', __( 'Sorry, you are not allowed to change the comment type.' ), array( 'status' => 404 ) );
684 $prepared_args = $this->prepare_item_for_database( $request );
686 if ( is_wp_error( $prepared_args ) ) {
687 return $prepared_args;
690 if ( ! empty( $prepared_args['comment_post_ID'] ) ) {
691 $post = get_post( $prepared_args['comment_post_ID'] );
692 if ( empty( $post ) ) {
693 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Invalid post ID.' ), array( 'status' => 403 ) );
697 if ( empty( $prepared_args ) && isset( $request['status'] ) ) {
698 // Only the comment status is being changed.
699 $change = $this->handle_status_param( $request['status'], $id );
702 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) );
704 } elseif ( ! empty( $prepared_args ) ) {
705 if ( is_wp_error( $prepared_args ) ) {
706 return $prepared_args;
709 if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) {
710 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
713 $prepared_args['comment_ID'] = $id;
715 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
716 if ( is_wp_error( $check_comment_lengths ) ) {
717 $error_code = $check_comment_lengths->get_error_code();
718 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
721 $updated = wp_update_comment( wp_slash( (array) $prepared_args ) );
723 if ( false === $updated ) {
724 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) );
727 if ( isset( $request['status'] ) ) {
728 $this->handle_status_param( $request['status'], $id );
732 $comment = get_comment( $id );
734 /* This action is documented in lib/endpoints/class-wp-rest-comments-controller.php */
735 do_action( 'rest_insert_comment', $comment, $request, false );
737 $schema = $this->get_item_schema();
739 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
740 $meta_update = $this->meta->update_value( $request['meta'], $id );
742 if ( is_wp_error( $meta_update ) ) {
747 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
749 if ( is_wp_error( $fields_update ) ) {
750 return $fields_update;
753 $request->set_param( 'context', 'edit' );
755 $response = $this->prepare_item_for_response( $comment, $request );
757 return rest_ensure_response( $response );
761 * Checks if a given request has access to delete a comment.
766 * @param WP_REST_Request $request Full details about the request.
767 * @return WP_Error|bool True if the request has access to delete the item, error object otherwise.
769 public function delete_item_permissions_check( $request ) {
770 $comment = $this->get_comment( $request['id'] );
771 if ( is_wp_error( $comment ) ) {
775 if ( ! $this->check_edit_permission( $comment ) ) {
776 return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) );
787 * @param WP_REST_Request $request Full details about the request.
788 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
790 public function delete_item( $request ) {
791 $comment = $this->get_comment( $request['id'] );
792 if ( is_wp_error( $comment ) ) {
796 $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
799 * Filters whether a comment can be trashed.
801 * Return false to disable trash support for the post.
805 * @param bool $supports_trash Whether the post type support trashing.
806 * @param WP_Post $comment The comment object being considered for trashing support.
808 $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
810 $request->set_param( 'context', 'edit' );
813 $previous = $this->prepare_item_for_response( $comment, $request );
814 $result = wp_delete_comment( $comment->comment_ID, true );
815 $response = new WP_REST_Response();
816 $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
818 // If this type doesn't support trashing, error out.
819 if ( ! $supports_trash ) {
820 return new WP_Error( 'rest_trash_not_supported', __( 'The comment does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
823 if ( 'trash' === $comment->comment_approved ) {
824 return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
827 $result = wp_trash_comment( $comment->comment_ID );
828 $comment = get_comment( $comment->comment_ID );
829 $response = $this->prepare_item_for_response( $comment, $request );
833 return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
837 * Fires after a comment is deleted via the REST API.
841 * @param WP_Comment $comment The deleted comment data.
842 * @param WP_REST_Response $response The response returned from the API.
843 * @param WP_REST_Request $request The request sent to the API.
845 do_action( 'rest_delete_comment', $comment, $response, $request );
851 * Prepares a single comment output for response.
856 * @param WP_Comment $comment Comment object.
857 * @param WP_REST_Request $request Request object.
858 * @return WP_REST_Response Response object.
860 public function prepare_item_for_response( $comment, $request ) {
862 'id' => (int) $comment->comment_ID,
863 'post' => (int) $comment->comment_post_ID,
864 'parent' => (int) $comment->comment_parent,
865 'author' => (int) $comment->user_id,
866 'author_name' => $comment->comment_author,
867 'author_email' => $comment->comment_author_email,
868 'author_url' => $comment->comment_author_url,
869 'author_ip' => $comment->comment_author_IP,
870 'author_user_agent' => $comment->comment_agent,
871 'date' => mysql_to_rfc3339( $comment->comment_date ),
872 'date_gmt' => mysql_to_rfc3339( $comment->comment_date_gmt ),
874 /** This filter is documented in wp-includes/comment-template.php */
875 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
876 'raw' => $comment->comment_content,
878 'link' => get_comment_link( $comment ),
879 'status' => $this->prepare_status_response( $comment->comment_approved ),
880 'type' => get_comment_type( $comment->comment_ID ),
883 $schema = $this->get_item_schema();
885 if ( ! empty( $schema['properties']['author_avatar_urls'] ) ) {
886 $data['author_avatar_urls'] = rest_get_avatar_urls( $comment->comment_author_email );
889 if ( ! empty( $schema['properties']['meta'] ) ) {
890 $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
893 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
894 $data = $this->add_additional_fields_to_object( $data, $request );
895 $data = $this->filter_response_by_context( $data, $context );
897 // Wrap the data in a response object.
898 $response = rest_ensure_response( $data );
900 $response->add_links( $this->prepare_links( $comment ) );
903 * Filters a comment returned from the API.
905 * Allows modification of the comment right before it is returned.
909 * @param WP_REST_Response $response The response object.
910 * @param WP_Comment $comment The original comment object.
911 * @param WP_REST_Request $request Request used to generate the response.
913 return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
917 * Prepares links for the request.
922 * @param WP_Comment $comment Comment object.
923 * @return array Links for the given comment.
925 protected function prepare_links( $comment ) {
928 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
930 'collection' => array(
931 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
935 if ( 0 !== (int) $comment->user_id ) {
936 $links['author'] = array(
937 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ),
938 'embeddable' => true,
942 if ( 0 !== (int) $comment->comment_post_ID ) {
943 $post = get_post( $comment->comment_post_ID );
945 if ( ! empty( $post->ID ) ) {
946 $obj = get_post_type_object( $post->post_type );
947 $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
949 $links['up'] = array(
950 'href' => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ),
951 'embeddable' => true,
952 'post_type' => $post->post_type,
957 if ( 0 !== (int) $comment->comment_parent ) {
958 $links['in-reply-to'] = array(
959 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
960 'embeddable' => true,
964 // Only grab one comment to verify the comment has children.
965 $comment_children = $comment->get_children( array(
970 if ( ! empty( $comment_children ) ) {
972 'parent' => $comment->comment_ID
975 $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
977 $links['children'] = array(
986 * Prepends internal property prefix to query parameters to match our response fields.
991 * @param string $query_param Query parameter.
992 * @return string The normalized query parameter.
994 protected function normalize_query_param( $query_param ) {
995 $prefix = 'comment_';
997 switch ( $query_param ) {
999 $normalized = $prefix . 'ID';
1002 $normalized = $prefix . 'post_ID';
1005 $normalized = $prefix . 'parent';
1008 $normalized = 'comment__in';
1011 $normalized = $prefix . $query_param;
1019 * Checks comment_approved to set comment status for single comment output.
1024 * @param string|int $comment_approved comment status.
1025 * @return string Comment status.
1027 protected function prepare_status_response( $comment_approved ) {
1029 switch ( $comment_approved ) {
1037 $status = 'approved';
1043 $status = $comment_approved;
1051 * Prepares a single comment to be inserted into the database.
1056 * @param WP_REST_Request $request Request object.
1057 * @return array|WP_Error Prepared comment, otherwise WP_Error object.
1059 protected function prepare_item_for_database( $request ) {
1060 $prepared_comment = array();
1063 * Allow the comment_content to be set via the 'content' or
1064 * the 'content.raw' properties of the Request object.
1066 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
1067 $prepared_comment['comment_content'] = $request['content'];
1068 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
1069 $prepared_comment['comment_content'] = $request['content']['raw'];
1072 if ( isset( $request['post'] ) ) {
1073 $prepared_comment['comment_post_ID'] = (int) $request['post'];
1076 if ( isset( $request['parent'] ) ) {
1077 $prepared_comment['comment_parent'] = $request['parent'];
1080 if ( isset( $request['author'] ) ) {
1081 $user = new WP_User( $request['author'] );
1083 if ( $user->exists() ) {
1084 $prepared_comment['user_id'] = $user->ID;
1085 $prepared_comment['comment_author'] = $user->display_name;
1086 $prepared_comment['comment_author_email'] = $user->user_email;
1087 $prepared_comment['comment_author_url'] = $user->user_url;
1089 return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) );
1093 if ( isset( $request['author_name'] ) ) {
1094 $prepared_comment['comment_author'] = $request['author_name'];
1097 if ( isset( $request['author_email'] ) ) {
1098 $prepared_comment['comment_author_email'] = $request['author_email'];
1101 if ( isset( $request['author_url'] ) ) {
1102 $prepared_comment['comment_author_url'] = $request['author_url'];
1105 if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
1106 $prepared_comment['comment_author_IP'] = $request['author_ip'];
1107 } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
1108 $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1110 $prepared_comment['comment_author_IP'] = '127.0.0.1';
1113 if ( ! empty( $request['author_user_agent'] ) ) {
1114 $prepared_comment['comment_agent'] = $request['author_user_agent'];
1115 } elseif ( $request->get_header( 'user_agent' ) ) {
1116 $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
1119 if ( ! empty( $request['date'] ) ) {
1120 $date_data = rest_get_date_with_gmt( $request['date'] );
1122 if ( ! empty( $date_data ) ) {
1123 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1125 } elseif ( ! empty( $request['date_gmt'] ) ) {
1126 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
1128 if ( ! empty( $date_data ) ) {
1129 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1134 * Filters a comment after it is prepared for the database.
1136 * Allows modification of the comment right after it is prepared for the database.
1140 * @param array $prepared_comment The prepared comment data for `wp_insert_comment`.
1141 * @param WP_REST_Request $request The current request.
1143 return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
1147 * Retrieves the comment's schema, conforming to JSON Schema.
1154 public function get_item_schema() {
1156 '$schema' => 'http://json-schema.org/schema#',
1157 'title' => 'comment',
1159 'properties' => array(
1161 'description' => __( 'Unique identifier for the object.' ),
1162 'type' => 'integer',
1163 'context' => array( 'view', 'edit', 'embed' ),
1167 'description' => __( 'The ID of the user object, if author was a user.' ),
1168 'type' => 'integer',
1169 'context' => array( 'view', 'edit', 'embed' ),
1171 'author_email' => array(
1172 'description' => __( 'Email address for the object author.' ),
1174 'format' => 'email',
1175 'context' => array( 'edit' ),
1176 'arg_options' => array(
1177 'sanitize_callback' => array( $this, 'check_comment_author_email' ),
1178 'validate_callback' => null, // skip built-in validation of 'email'.
1181 'author_ip' => array(
1182 'description' => __( 'IP address for the object author.' ),
1185 'context' => array( 'edit' ),
1187 'author_name' => array(
1188 'description' => __( 'Display name for the object author.' ),
1190 'context' => array( 'view', 'edit', 'embed' ),
1191 'arg_options' => array(
1192 'sanitize_callback' => 'sanitize_text_field',
1195 'author_url' => array(
1196 'description' => __( 'URL for the object author.' ),
1199 'context' => array( 'view', 'edit', 'embed' ),
1201 'author_user_agent' => array(
1202 'description' => __( 'User agent for the object author.' ),
1204 'context' => array( 'edit' ),
1205 'arg_options' => array(
1206 'sanitize_callback' => 'sanitize_text_field',
1210 'description' => __( 'The content for the object.' ),
1212 'context' => array( 'view', 'edit', 'embed' ),
1213 'arg_options' => array(
1214 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1216 'properties' => array(
1218 'description' => __( 'Content for the object, as it exists in the database.' ),
1220 'context' => array( 'edit' ),
1222 'rendered' => array(
1223 'description' => __( 'HTML content for the object, transformed for display.' ),
1225 'context' => array( 'view', 'edit', 'embed' ),
1231 'description' => __( "The date the object was published, in the site's timezone." ),
1233 'format' => 'date-time',
1234 'context' => array( 'view', 'edit', 'embed' ),
1236 'date_gmt' => array(
1237 'description' => __( 'The date the object was published, as GMT.' ),
1239 'format' => 'date-time',
1240 'context' => array( 'view', 'edit' ),
1243 'description' => __( 'URL to the object.' ),
1246 'context' => array( 'view', 'edit', 'embed' ),
1250 'description' => __( 'The ID for the parent of the object.' ),
1251 'type' => 'integer',
1252 'context' => array( 'view', 'edit', 'embed' ),
1256 'description' => __( 'The ID of the associated post object.' ),
1257 'type' => 'integer',
1258 'context' => array( 'view', 'edit' ),
1262 'description' => __( 'State of the object.' ),
1264 'context' => array( 'view', 'edit' ),
1265 'arg_options' => array(
1266 'sanitize_callback' => 'sanitize_key',
1270 'description' => __( 'Type of Comment for the object.' ),
1272 'context' => array( 'view', 'edit', 'embed' ),
1278 if ( get_option( 'show_avatars' ) ) {
1279 $avatar_properties = array();
1281 $avatar_sizes = rest_get_avatar_sizes();
1282 foreach ( $avatar_sizes as $size ) {
1283 $avatar_properties[ $size ] = array(
1284 /* translators: %d: avatar image size in pixels */
1285 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
1288 'context' => array( 'embed', 'view', 'edit' ),
1292 $schema['properties']['author_avatar_urls'] = array(
1293 'description' => __( 'Avatar URLs for the object author.' ),
1295 'context' => array( 'view', 'edit', 'embed' ),
1297 'properties' => $avatar_properties,
1301 $schema['properties']['meta'] = $this->meta->get_field_schema();
1303 return $this->add_additional_fields_schema( $schema );
1307 * Retrieves the query params for collections.
1312 * @return array Comments collection parameters.
1314 public function get_collection_params() {
1315 $query_params = parent::get_collection_params();
1317 $query_params['context']['default'] = 'view';
1319 $query_params['after'] = array(
1320 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
1322 'format' => 'date-time',
1325 $query_params['author'] = array(
1326 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
1329 'type' => 'integer',
1333 $query_params['author_exclude'] = array(
1334 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
1337 'type' => 'integer',
1341 $query_params['author_email'] = array(
1343 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
1344 'format' => 'email',
1348 $query_params['before'] = array(
1349 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
1351 'format' => 'date-time',
1354 $query_params['exclude'] = array(
1355 'description' => __( 'Ensure result set excludes specific IDs.' ),
1358 'type' => 'integer',
1360 'default' => array(),
1363 $query_params['include'] = array(
1364 'description' => __( 'Limit result set to specific IDs.' ),
1367 'type' => 'integer',
1369 'default' => array(),
1372 $query_params['offset'] = array(
1373 'description' => __( 'Offset the result set by a specific number of items.' ),
1374 'type' => 'integer',
1377 $query_params['order'] = array(
1378 'description' => __( 'Order sort attribute ascending or descending.' ),
1380 'default' => 'desc',
1387 $query_params['orderby'] = array(
1388 'description' => __( 'Sort collection by object attribute.' ),
1390 'default' => 'date_gmt',
1402 $query_params['parent'] = array(
1403 'default' => array(),
1404 'description' => __( 'Limit result set to comments of specific parent IDs.' ),
1407 'type' => 'integer',
1411 $query_params['parent_exclude'] = array(
1412 'default' => array(),
1413 'description' => __( 'Ensure result set excludes specific parent IDs.' ),
1416 'type' => 'integer',
1420 $query_params['post'] = array(
1421 'default' => array(),
1422 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ),
1425 'type' => 'integer',
1429 $query_params['status'] = array(
1430 'default' => 'approve',
1431 'description' => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ),
1432 'sanitize_callback' => 'sanitize_key',
1434 'validate_callback' => 'rest_validate_request_arg',
1437 $query_params['type'] = array(
1438 'default' => 'comment',
1439 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
1440 'sanitize_callback' => 'sanitize_key',
1442 'validate_callback' => 'rest_validate_request_arg',
1445 $query_params['password'] = array(
1446 'description' => __( 'The password for the post if it is password protected.' ),
1451 * Filter collection parameters for the comments controller.
1453 * This filter registers the collection parameter, but does not map the
1454 * collection parameter to an internal WP_Comment_Query parameter. Use the
1455 * `rest_comment_query` filter to set WP_Comment_Query parameters.
1459 * @param array $query_params JSON Schema-formatted collection parameters.
1461 return apply_filters( 'rest_comment_collection_params', $query_params );
1465 * Sets the comment_status of a given comment object when creating or updating a comment.
1470 * @param string|int $new_status New comment status.
1471 * @param int $comment_id Comment ID.
1472 * @return bool Whether the status was changed.
1474 protected function handle_status_param( $new_status, $comment_id ) {
1475 $old_status = wp_get_comment_status( $comment_id );
1477 if ( $new_status === $old_status ) {
1481 switch ( $new_status ) {
1485 $changed = wp_set_comment_status( $comment_id, 'approve' );
1489 $changed = wp_set_comment_status( $comment_id, 'hold' );
1492 $changed = wp_spam_comment( $comment_id );
1495 $changed = wp_unspam_comment( $comment_id );
1498 $changed = wp_trash_comment( $comment_id );
1501 $changed = wp_untrash_comment( $comment_id );
1512 * Checks if the post can be read.
1514 * Correctly handles posts with the inherit status.
1519 * @param WP_Post $post Post object.
1520 * @param WP_REST_Request $request Request data to check.
1521 * @return bool Whether post can be read.
1523 protected function check_read_post_permission( $post, $request ) {
1524 $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
1525 $post_type = get_post_type_object( $post->post_type );
1527 $has_password_filter = false;
1529 // Only check password if a specific post was queried for or a single comment
1530 $requested_post = ! empty( $request['post'] ) && 1 === count( $request['post'] );
1531 $requested_comment = ! empty( $request['id'] );
1532 if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
1533 add_filter( 'post_password_required', '__return_false' );
1535 $has_password_filter = true;
1538 if ( post_password_required( $post ) ) {
1539 $result = current_user_can( $post_type->cap->edit_post, $post->ID );
1541 $result = $posts_controller->check_read_permission( $post );
1544 if ( $has_password_filter ) {
1545 remove_filter( 'post_password_required', '__return_false' );
1552 * Checks if the comment can be read.
1557 * @param WP_Comment $comment Comment object.
1558 * @param WP_REST_Request $request Request data to check.
1559 * @return bool Whether the comment can be read.
1561 protected function check_read_permission( $comment, $request ) {
1562 if ( ! empty( $comment->comment_post_ID ) ) {
1563 $post = get_post( $comment->comment_post_ID );
1565 if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
1571 if ( 0 === get_current_user_id() ) {
1575 if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
1579 if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
1583 return current_user_can( 'edit_comment', $comment->comment_ID );
1587 * Checks if a comment can be edited or deleted.
1592 * @param object $comment Comment object.
1593 * @return bool Whether the comment can be edited or deleted.
1595 protected function check_edit_permission( $comment ) {
1596 if ( 0 === (int) get_current_user_id() ) {
1600 if ( ! current_user_can( 'moderate_comments' ) ) {
1604 return current_user_can( 'edit_comment', $comment->comment_ID );
1608 * Checks a comment author email for validity.
1610 * Accepts either a valid email address or empty string as a valid comment
1611 * author email address. Setting the comment author email to an empty
1612 * string is allowed when a comment is being updated.
1616 * @param string $value Author email value submitted.
1617 * @param WP_REST_Request $request Full details about the request.
1618 * @param string $param The parameter name.
1619 * @return WP_Error|string The sanitized email address, if valid,
1620 * otherwise an error.
1622 public function check_comment_author_email( $value, $request, $param ) {
1623 $email = (string) $value;
1624 if ( empty( $email ) ) {
1628 $check_email = rest_validate_request_arg( $email, $request, $param );
1629 if ( is_wp_error( $check_email ) ) {
1630 return $check_email;