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(
67 'methods' => WP_REST_Server::READABLE,
68 'callback' => array( $this, 'get_item' ),
69 'permission_callback' => array( $this, 'get_item_permissions_check' ),
71 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
73 'description' => __( 'The password for the post if it is password protected.' ),
79 'methods' => WP_REST_Server::EDITABLE,
80 'callback' => array( $this, 'update_item' ),
81 'permission_callback' => array( $this, 'update_item_permissions_check' ),
82 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
85 'methods' => WP_REST_Server::DELETABLE,
86 'callback' => array( $this, 'delete_item' ),
87 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
92 'description' => __( 'Whether to bypass trash and force deletion.' ),
95 'description' => __( 'The password for the post if it is password protected.' ),
100 'schema' => array( $this, 'get_public_item_schema' ),
105 * Checks if a given request has access to read comments.
110 * @param WP_REST_Request $request Full details about the request.
111 * @return WP_Error|bool True if the request has read access, error object otherwise.
113 public function get_items_permissions_check( $request ) {
115 if ( ! empty( $request['post'] ) ) {
116 foreach ( (array) $request['post'] as $post_id ) {
117 $post = get_post( $post_id );
119 if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post, $request ) ) {
120 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() ) );
121 } elseif ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) {
122 return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read comments without a post.' ), array( 'status' => rest_authorization_required_code() ) );
127 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
128 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
131 if ( ! current_user_can( 'edit_posts' ) ) {
132 $protected_params = array( 'author', 'author_exclude', 'author_email', 'type', 'status' );
133 $forbidden_params = array();
135 foreach ( $protected_params as $param ) {
136 if ( 'status' === $param ) {
137 if ( 'approve' !== $request[ $param ] ) {
138 $forbidden_params[] = $param;
140 } elseif ( 'type' === $param ) {
141 if ( 'comment' !== $request[ $param ] ) {
142 $forbidden_params[] = $param;
144 } elseif ( ! empty( $request[ $param ] ) ) {
145 $forbidden_params[] = $param;
149 if ( ! empty( $forbidden_params ) ) {
150 return new WP_Error( 'rest_forbidden_param', sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ), array( 'status' => rest_authorization_required_code() ) );
158 * Retrieves a list of comment items.
163 * @param WP_REST_Request $request Full details about the request.
164 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
166 public function get_items( $request ) {
168 // Retrieve the list of registered collection query parameters.
169 $registered = $this->get_collection_params();
172 * This array defines mappings between public API query parameters whose
173 * values are accepted as-passed, and their internal WP_Query parameter
174 * name equivalents (some are the same). Only values which are also
175 * present in $registered will be set.
177 $parameter_mappings = array(
178 'author' => 'author__in',
179 'author_email' => 'author_email',
180 'author_exclude' => 'author__not_in',
181 'exclude' => 'comment__not_in',
182 'include' => 'comment__in',
183 'offset' => 'offset',
185 'parent' => 'parent__in',
186 'parent_exclude' => 'parent__not_in',
187 'per_page' => 'number',
188 'post' => 'post__in',
189 'search' => 'search',
190 'status' => 'status',
194 $prepared_args = array();
197 * For each known parameter which is both registered and present in the request,
198 * set the parameter's value on the query $prepared_args.
200 foreach ( $parameter_mappings as $api_param => $wp_param ) {
201 if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
202 $prepared_args[ $wp_param ] = $request[ $api_param ];
206 // Ensure certain parameter values default to empty strings.
207 foreach ( array( 'author_email', 'search' ) as $param ) {
208 if ( ! isset( $prepared_args[ $param ] ) ) {
209 $prepared_args[ $param ] = '';
213 if ( isset( $registered['orderby'] ) ) {
214 $prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] );
217 $prepared_args['no_found_rows'] = false;
219 $prepared_args['date_query'] = array();
221 // Set before into date query. Date query must be specified as an array of an array.
222 if ( isset( $registered['before'], $request['before'] ) ) {
223 $prepared_args['date_query'][0]['before'] = $request['before'];
226 // Set after into date query. Date query must be specified as an array of an array.
227 if ( isset( $registered['after'], $request['after'] ) ) {
228 $prepared_args['date_query'][0]['after'] = $request['after'];
231 if ( isset( $registered['page'] ) && empty( $request['offset'] ) ) {
232 $prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 );
236 * Filters arguments, before passing to WP_Comment_Query, when querying comments via the REST API.
240 * @link https://developer.wordpress.org/reference/classes/wp_comment_query/
242 * @param array $prepared_args Array of arguments for WP_Comment_Query.
243 * @param WP_REST_Request $request The current request.
245 $prepared_args = apply_filters( 'rest_comment_query', $prepared_args, $request );
247 $query = new WP_Comment_Query;
248 $query_result = $query->query( $prepared_args );
252 foreach ( $query_result as $comment ) {
253 if ( ! $this->check_read_permission( $comment, $request ) ) {
257 $data = $this->prepare_item_for_response( $comment, $request );
258 $comments[] = $this->prepare_response_for_collection( $data );
261 $total_comments = (int) $query->found_comments;
262 $max_pages = (int) $query->max_num_pages;
264 if ( $total_comments < 1 ) {
265 // Out-of-bounds, run the query again without LIMIT for total count.
266 unset( $prepared_args['number'], $prepared_args['offset'] );
268 $query = new WP_Comment_Query;
269 $prepared_args['count'] = true;
271 $total_comments = $query->query( $prepared_args );
272 $max_pages = ceil( $total_comments / $request['per_page'] );
275 $response = rest_ensure_response( $comments );
276 $response->header( 'X-WP-Total', $total_comments );
277 $response->header( 'X-WP-TotalPages', $max_pages );
279 $base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
281 if ( $request['page'] > 1 ) {
282 $prev_page = $request['page'] - 1;
284 if ( $prev_page > $max_pages ) {
285 $prev_page = $max_pages;
288 $prev_link = add_query_arg( 'page', $prev_page, $base );
289 $response->link_header( 'prev', $prev_link );
292 if ( $max_pages > $request['page'] ) {
293 $next_page = $request['page'] + 1;
294 $next_link = add_query_arg( 'page', $next_page, $base );
296 $response->link_header( 'next', $next_link );
303 * Checks if a given request has access to read the comment.
308 * @param WP_REST_Request $request Full details about the request.
309 * @return WP_Error|bool True if the request has read access for the item, error object otherwise.
311 public function get_item_permissions_check( $request ) {
312 $id = (int) $request['id'];
314 $comment = get_comment( $id );
320 if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) {
321 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) );
324 $post = get_post( $comment->comment_post_ID );
326 if ( ! $this->check_read_permission( $comment, $request ) ) {
327 return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read this comment.' ), array( 'status' => rest_authorization_required_code() ) );
330 if ( $post && ! $this->check_read_post_permission( $post, $request ) ) {
331 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() ) );
338 * Retrieves a comment.
343 * @param WP_REST_Request $request Full details about the request.
344 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
346 public function get_item( $request ) {
347 $id = (int) $request['id'];
349 $comment = get_comment( $id );
350 if ( empty( $comment ) ) {
351 return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
354 if ( ! empty( $comment->comment_post_ID ) ) {
355 $post = get_post( $comment->comment_post_ID );
356 if ( empty( $post ) ) {
357 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
361 $data = $this->prepare_item_for_response( $comment, $request );
362 $response = rest_ensure_response( $data );
368 * Checks if a given request has access to create a comment.
373 * @param WP_REST_Request $request Full details about the request.
374 * @return WP_Error|bool True if the request has access to create items, error object otherwise.
376 public function create_item_permissions_check( $request ) {
377 if ( ! is_user_logged_in() ) {
378 if ( get_option( 'comment_registration' ) ) {
379 return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
383 * Filter whether comments can be created without authentication.
385 * Enables creating comments for anonymous users.
389 * @param bool $allow_anonymous Whether to allow anonymous comments to
390 * be created. Default `false`.
391 * @param WP_REST_Request $request Request used to generate the
394 $allow_anonymous = apply_filters( 'rest_allow_anonymous_comments', false, $request );
395 if ( ! $allow_anonymous ) {
396 return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) );
400 // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default.
401 if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) {
402 return new WP_Error( 'rest_comment_invalid_author',
403 /* translators: %s: request parameter */
404 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ),
405 array( 'status' => rest_authorization_required_code() )
409 if ( isset( $request['author_ip'] ) && ! current_user_can( 'moderate_comments' ) ) {
410 if ( empty( $_SERVER['REMOTE_ADDR'] ) || $request['author_ip'] !== $_SERVER['REMOTE_ADDR'] ) {
411 return new WP_Error( 'rest_comment_invalid_author_ip',
412 /* translators: %s: request parameter */
413 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author_ip' ),
414 array( 'status' => rest_authorization_required_code() )
419 if ( isset( $request['status'] ) && ! current_user_can( 'moderate_comments' ) ) {
420 return new WP_Error( 'rest_comment_invalid_status',
421 /* translators: %s: request parameter */
422 sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'status' ),
423 array( 'status' => rest_authorization_required_code() )
427 if ( empty( $request['post'] ) ) {
428 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
431 $post = get_post( (int) $request['post'] );
433 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) );
436 if ( 'draft' === $post->post_status ) {
437 return new WP_Error( 'rest_comment_draft_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
440 if ( 'trash' === $post->post_status ) {
441 return new WP_Error( 'rest_comment_trash_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) );
444 if ( ! $this->check_read_post_permission( $post, $request ) ) {
445 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() ) );
448 if ( ! comments_open( $post->ID ) ) {
449 return new WP_Error( 'rest_comment_closed', __( 'Sorry, comments are closed for this item.' ), array( 'status' => 403 ) );
461 * @param WP_REST_Request $request Full details about the request.
462 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
464 public function create_item( $request ) {
465 if ( ! empty( $request['id'] ) ) {
466 return new WP_Error( 'rest_comment_exists', __( 'Cannot create existing comment.' ), array( 'status' => 400 ) );
469 // Do not allow comments to be created with a non-default type.
470 if ( ! empty( $request['type'] ) && 'comment' !== $request['type'] ) {
471 return new WP_Error( 'rest_invalid_comment_type', __( 'Cannot create a comment with that type.' ), array( 'status' => 400 ) );
474 $prepared_comment = $this->prepare_item_for_database( $request );
475 if ( is_wp_error( $prepared_comment ) ) {
476 return $prepared_comment;
479 $prepared_comment['comment_type'] = '';
482 * Do not allow a comment to be created with missing or empty
483 * comment_content. See wp_handle_comment_submission().
485 if ( empty( $prepared_comment['comment_content'] ) ) {
486 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
489 // Setting remaining values before wp_insert_comment so we can use wp_allow_comment().
490 if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) {
491 $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true );
494 // Set author data if the user's logged in.
495 $missing_author = empty( $prepared_comment['user_id'] )
496 && empty( $prepared_comment['comment_author'] )
497 && empty( $prepared_comment['comment_author_email'] )
498 && empty( $prepared_comment['comment_author_url'] );
500 if ( is_user_logged_in() && $missing_author ) {
501 $user = wp_get_current_user();
503 $prepared_comment['user_id'] = $user->ID;
504 $prepared_comment['comment_author'] = $user->display_name;
505 $prepared_comment['comment_author_email'] = $user->user_email;
506 $prepared_comment['comment_author_url'] = $user->user_url;
509 // Honor the discussion setting that requires a name and email address of the comment author.
510 if ( get_option( 'require_name_email' ) ) {
511 if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) {
512 return new WP_Error( 'rest_comment_author_data_required', __( 'Creating a comment requires valid author name and email values.' ), array( 'status' => 400 ) );
516 if ( ! isset( $prepared_comment['comment_author_email'] ) ) {
517 $prepared_comment['comment_author_email'] = '';
520 if ( ! isset( $prepared_comment['comment_author_url'] ) ) {
521 $prepared_comment['comment_author_url'] = '';
524 if ( ! isset( $prepared_comment['comment_agent'] ) ) {
525 $prepared_comment['comment_agent'] = '';
528 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment );
529 if ( is_wp_error( $check_comment_lengths ) ) {
530 $error_code = $check_comment_lengths->get_error_code();
531 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
534 $prepared_comment['comment_approved'] = wp_allow_comment( $prepared_comment, true );
536 if ( is_wp_error( $prepared_comment['comment_approved'] ) ) {
537 $error_code = $prepared_comment['comment_approved']->get_error_code();
538 $error_message = $prepared_comment['comment_approved']->get_error_message();
540 if ( 'comment_duplicate' === $error_code ) {
541 return new WP_Error( $error_code, $error_message, array( 'status' => 409 ) );
544 if ( 'comment_flood' === $error_code ) {
545 return new WP_Error( $error_code, $error_message, array( 'status' => 400 ) );
548 return $prepared_comment['comment_approved'];
552 * Filters a comment before it is inserted via the REST API.
554 * Allows modification of the comment right before it is inserted via wp_insert_comment().
558 * @param array $prepared_comment The prepared comment data for wp_insert_comment().
559 * @param WP_REST_Request $request Request used to insert the comment.
561 $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request );
563 $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) );
565 if ( ! $comment_id ) {
566 return new WP_Error( 'rest_comment_failed_create', __( 'Creating comment failed.' ), array( 'status' => 500 ) );
569 if ( isset( $request['status'] ) ) {
570 $this->handle_status_param( $request['status'], $comment_id );
573 $comment = get_comment( $comment_id );
576 * Fires after a comment is created or updated via the REST API.
580 * @param WP_Comment $comment Inserted or updated comment object.
581 * @param WP_REST_Request $request Request object.
582 * @param bool $creating True when creating a comment, false
585 do_action( 'rest_insert_comment', $comment, $request, true );
587 $schema = $this->get_item_schema();
589 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
590 $meta_update = $this->meta->update_value( $request['meta'], $comment_id );
592 if ( is_wp_error( $meta_update ) ) {
597 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
599 if ( is_wp_error( $fields_update ) ) {
600 return $fields_update;
603 $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view';
605 $request->set_param( 'context', $context );
607 $response = $this->prepare_item_for_response( $comment, $request );
608 $response = rest_ensure_response( $response );
610 $response->set_status( 201 );
611 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) );
618 * Checks if a given REST request has access to update a comment.
623 * @param WP_REST_Request $request Full details about the request.
624 * @return WP_Error|bool True if the request has access to update the item, error object otherwise.
626 public function update_item_permissions_check( $request ) {
628 $id = (int) $request['id'];
630 $comment = get_comment( $id );
632 if ( $comment && ! $this->check_edit_permission( $comment ) ) {
633 return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this comment.' ), array( 'status' => rest_authorization_required_code() ) );
645 * @param WP_REST_Request $request Full details about the request.
646 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
648 public function update_item( $request ) {
649 $id = (int) $request['id'];
651 $comment = get_comment( $id );
653 if ( empty( $comment ) ) {
654 return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
657 if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) {
658 return new WP_Error( 'rest_comment_invalid_type', __( 'Sorry, you are not allowed to change the comment type.' ), array( 'status' => 404 ) );
661 $prepared_args = $this->prepare_item_for_database( $request );
663 if ( is_wp_error( $prepared_args ) ) {
664 return $prepared_args;
667 if ( ! empty( $prepared_args['comment_post_ID'] ) ) {
668 $post = get_post( $prepared_args['comment_post_ID'] );
669 if ( empty( $post ) ) {
670 return new WP_Error( 'rest_comment_invalid_post_id', __( 'Invalid post ID.' ), array( 'status' => 403 ) );
674 if ( empty( $prepared_args ) && isset( $request['status'] ) ) {
675 // Only the comment status is being changed.
676 $change = $this->handle_status_param( $request['status'], $id );
679 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) );
681 } elseif ( ! empty( $prepared_args ) ) {
682 if ( is_wp_error( $prepared_args ) ) {
683 return $prepared_args;
686 if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) {
687 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
690 $prepared_args['comment_ID'] = $id;
692 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
693 if ( is_wp_error( $check_comment_lengths ) ) {
694 $error_code = $check_comment_lengths->get_error_code();
695 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
698 $updated = wp_update_comment( wp_slash( (array) $prepared_args ) );
700 if ( false === $updated ) {
701 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) );
704 if ( isset( $request['status'] ) ) {
705 $this->handle_status_param( $request['status'], $id );
709 $comment = get_comment( $id );
711 /* This action is documented in lib/endpoints/class-wp-rest-comments-controller.php */
712 do_action( 'rest_insert_comment', $comment, $request, false );
714 $schema = $this->get_item_schema();
716 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
717 $meta_update = $this->meta->update_value( $request['meta'], $id );
719 if ( is_wp_error( $meta_update ) ) {
724 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
726 if ( is_wp_error( $fields_update ) ) {
727 return $fields_update;
730 $request->set_param( 'context', 'edit' );
732 $response = $this->prepare_item_for_response( $comment, $request );
734 return rest_ensure_response( $response );
738 * Checks if a given request has access to delete a comment.
743 * @param WP_REST_Request $request Full details about the request.
744 * @return WP_Error|bool True if the request has access to delete the item, error object otherwise.
746 public function delete_item_permissions_check( $request ) {
747 $id = (int) $request['id'];
748 $comment = get_comment( $id );
751 return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
754 if ( ! $this->check_edit_permission( $comment ) ) {
755 return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) );
766 * @param WP_REST_Request $request Full details about the request.
767 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
769 public function delete_item( $request ) {
770 $id = (int) $request['id'];
771 $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
773 $comment = get_comment( $id );
775 if ( empty( $comment ) ) {
776 return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
780 * Filters whether a comment can be trashed.
782 * Return false to disable trash support for the post.
786 * @param bool $supports_trash Whether the post type support trashing.
787 * @param WP_Post $comment The comment object being considered for trashing support.
789 $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
791 $request->set_param( 'context', 'edit' );
794 $previous = $this->prepare_item_for_response( $comment, $request );
795 $result = wp_delete_comment( $comment->comment_ID, true );
796 $response = new WP_REST_Response();
797 $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
799 // If this type doesn't support trashing, error out.
800 if ( ! $supports_trash ) {
801 return new WP_Error( 'rest_trash_not_supported', __( 'The comment does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
804 if ( 'trash' === $comment->comment_approved ) {
805 return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
808 $result = wp_trash_comment( $comment->comment_ID );
809 $comment = get_comment( $comment->comment_ID );
810 $response = $this->prepare_item_for_response( $comment, $request );
814 return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
818 * Fires after a comment is deleted via the REST API.
822 * @param WP_Comment $comment The deleted comment data.
823 * @param WP_REST_Response $response The response returned from the API.
824 * @param WP_REST_Request $request The request sent to the API.
826 do_action( 'rest_delete_comment', $comment, $response, $request );
832 * Prepares a single comment output for response.
837 * @param WP_Comment $comment Comment object.
838 * @param WP_REST_Request $request Request object.
839 * @return WP_REST_Response Response object.
841 public function prepare_item_for_response( $comment, $request ) {
843 'id' => (int) $comment->comment_ID,
844 'post' => (int) $comment->comment_post_ID,
845 'parent' => (int) $comment->comment_parent,
846 'author' => (int) $comment->user_id,
847 'author_name' => $comment->comment_author,
848 'author_email' => $comment->comment_author_email,
849 'author_url' => $comment->comment_author_url,
850 'author_ip' => $comment->comment_author_IP,
851 'author_user_agent' => $comment->comment_agent,
852 'date' => mysql_to_rfc3339( $comment->comment_date ),
853 'date_gmt' => mysql_to_rfc3339( $comment->comment_date_gmt ),
855 /** This filter is documented in wp-includes/comment-template.php */
856 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
857 'raw' => $comment->comment_content,
859 'link' => get_comment_link( $comment ),
860 'status' => $this->prepare_status_response( $comment->comment_approved ),
861 'type' => get_comment_type( $comment->comment_ID ),
864 $schema = $this->get_item_schema();
866 if ( ! empty( $schema['properties']['author_avatar_urls'] ) ) {
867 $data['author_avatar_urls'] = rest_get_avatar_urls( $comment->comment_author_email );
870 if ( ! empty( $schema['properties']['meta'] ) ) {
871 $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
874 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
875 $data = $this->add_additional_fields_to_object( $data, $request );
876 $data = $this->filter_response_by_context( $data, $context );
878 // Wrap the data in a response object.
879 $response = rest_ensure_response( $data );
881 $response->add_links( $this->prepare_links( $comment ) );
884 * Filters a comment returned from the API.
886 * Allows modification of the comment right before it is returned.
890 * @param WP_REST_Response $response The response object.
891 * @param WP_Comment $comment The original comment object.
892 * @param WP_REST_Request $request Request used to generate the response.
894 return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
898 * Prepares links for the request.
903 * @param WP_Comment $comment Comment object.
904 * @return array Links for the given comment.
906 protected function prepare_links( $comment ) {
909 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
911 'collection' => array(
912 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
916 if ( 0 !== (int) $comment->user_id ) {
917 $links['author'] = array(
918 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ),
919 'embeddable' => true,
923 if ( 0 !== (int) $comment->comment_post_ID ) {
924 $post = get_post( $comment->comment_post_ID );
926 if ( ! empty( $post->ID ) ) {
927 $obj = get_post_type_object( $post->post_type );
928 $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
930 $links['up'] = array(
931 'href' => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ),
932 'embeddable' => true,
933 'post_type' => $post->post_type,
938 if ( 0 !== (int) $comment->comment_parent ) {
939 $links['in-reply-to'] = array(
940 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
941 'embeddable' => true,
945 // Only grab one comment to verify the comment has children.
946 $comment_children = $comment->get_children( array(
951 if ( ! empty( $comment_children ) ) {
953 'parent' => $comment->comment_ID
956 $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
958 $links['children'] = array(
967 * Prepends internal property prefix to query parameters to match our response fields.
972 * @param string $query_param Query parameter.
973 * @return string The normalized query parameter.
975 protected function normalize_query_param( $query_param ) {
976 $prefix = 'comment_';
978 switch ( $query_param ) {
980 $normalized = $prefix . 'ID';
983 $normalized = $prefix . 'post_ID';
986 $normalized = $prefix . 'parent';
989 $normalized = 'comment__in';
992 $normalized = $prefix . $query_param;
1000 * Checks comment_approved to set comment status for single comment output.
1005 * @param string|int $comment_approved comment status.
1006 * @return string Comment status.
1008 protected function prepare_status_response( $comment_approved ) {
1010 switch ( $comment_approved ) {
1018 $status = 'approved';
1024 $status = $comment_approved;
1032 * Prepares a single comment to be inserted into the database.
1037 * @param WP_REST_Request $request Request object.
1038 * @return array|WP_Error Prepared comment, otherwise WP_Error object.
1040 protected function prepare_item_for_database( $request ) {
1041 $prepared_comment = array();
1044 * Allow the comment_content to be set via the 'content' or
1045 * the 'content.raw' properties of the Request object.
1047 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
1048 $prepared_comment['comment_content'] = $request['content'];
1049 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
1050 $prepared_comment['comment_content'] = $request['content']['raw'];
1053 if ( isset( $request['post'] ) ) {
1054 $prepared_comment['comment_post_ID'] = (int) $request['post'];
1057 if ( isset( $request['parent'] ) ) {
1058 $prepared_comment['comment_parent'] = $request['parent'];
1061 if ( isset( $request['author'] ) ) {
1062 $user = new WP_User( $request['author'] );
1064 if ( $user->exists() ) {
1065 $prepared_comment['user_id'] = $user->ID;
1066 $prepared_comment['comment_author'] = $user->display_name;
1067 $prepared_comment['comment_author_email'] = $user->user_email;
1068 $prepared_comment['comment_author_url'] = $user->user_url;
1070 return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) );
1074 if ( isset( $request['author_name'] ) ) {
1075 $prepared_comment['comment_author'] = $request['author_name'];
1078 if ( isset( $request['author_email'] ) ) {
1079 $prepared_comment['comment_author_email'] = $request['author_email'];
1082 if ( isset( $request['author_url'] ) ) {
1083 $prepared_comment['comment_author_url'] = $request['author_url'];
1086 if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
1087 $prepared_comment['comment_author_IP'] = $request['author_ip'];
1088 } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
1089 $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1091 $prepared_comment['comment_author_IP'] = '127.0.0.1';
1094 if ( ! empty( $request['author_user_agent'] ) ) {
1095 $prepared_comment['comment_agent'] = $request['author_user_agent'];
1096 } elseif ( $request->get_header( 'user_agent' ) ) {
1097 $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
1100 if ( ! empty( $request['date'] ) ) {
1101 $date_data = rest_get_date_with_gmt( $request['date'] );
1103 if ( ! empty( $date_data ) ) {
1104 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1106 } elseif ( ! empty( $request['date_gmt'] ) ) {
1107 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
1109 if ( ! empty( $date_data ) ) {
1110 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1115 * Filters a comment after it is prepared for the database.
1117 * Allows modification of the comment right after it is prepared for the database.
1121 * @param array $prepared_comment The prepared comment data for `wp_insert_comment`.
1122 * @param WP_REST_Request $request The current request.
1124 return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
1128 * Retrieves the comment's schema, conforming to JSON Schema.
1135 public function get_item_schema() {
1137 '$schema' => 'http://json-schema.org/schema#',
1138 'title' => 'comment',
1140 'properties' => array(
1142 'description' => __( 'Unique identifier for the object.' ),
1143 'type' => 'integer',
1144 'context' => array( 'view', 'edit', 'embed' ),
1148 'description' => __( 'The ID of the user object, if author was a user.' ),
1149 'type' => 'integer',
1150 'context' => array( 'view', 'edit', 'embed' ),
1152 'author_email' => array(
1153 'description' => __( 'Email address for the object author.' ),
1155 'format' => 'email',
1156 'context' => array( 'edit' ),
1157 'arg_options' => array(
1158 'sanitize_callback' => array( $this, 'check_comment_author_email' ),
1159 'validate_callback' => null, // skip built-in validation of 'email'.
1162 'author_ip' => array(
1163 'description' => __( 'IP address for the object author.' ),
1166 'context' => array( 'edit' ),
1168 'author_name' => array(
1169 'description' => __( 'Display name for the object author.' ),
1171 'context' => array( 'view', 'edit', 'embed' ),
1172 'arg_options' => array(
1173 'sanitize_callback' => 'sanitize_text_field',
1176 'author_url' => array(
1177 'description' => __( 'URL for the object author.' ),
1180 'context' => array( 'view', 'edit', 'embed' ),
1182 'author_user_agent' => array(
1183 'description' => __( 'User agent for the object author.' ),
1185 'context' => array( 'edit' ),
1186 'arg_options' => array(
1187 'sanitize_callback' => 'sanitize_text_field',
1191 'description' => __( 'The content for the object.' ),
1193 'context' => array( 'view', 'edit', 'embed' ),
1194 'arg_options' => array(
1195 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1197 'properties' => array(
1199 'description' => __( 'Content for the object, as it exists in the database.' ),
1201 'context' => array( 'edit' ),
1203 'rendered' => array(
1204 'description' => __( 'HTML content for the object, transformed for display.' ),
1206 'context' => array( 'view', 'edit', 'embed' ),
1212 'description' => __( "The date the object was published, in the site's timezone." ),
1214 'format' => 'date-time',
1215 'context' => array( 'view', 'edit', 'embed' ),
1217 'date_gmt' => array(
1218 'description' => __( 'The date the object was published, as GMT.' ),
1220 'format' => 'date-time',
1221 'context' => array( 'view', 'edit' ),
1224 'description' => __( 'URL to the object.' ),
1227 'context' => array( 'view', 'edit', 'embed' ),
1231 'description' => __( 'The ID for the parent of the object.' ),
1232 'type' => 'integer',
1233 'context' => array( 'view', 'edit', 'embed' ),
1237 'description' => __( 'The ID of the associated post object.' ),
1238 'type' => 'integer',
1239 'context' => array( 'view', 'edit' ),
1243 'description' => __( 'State of the object.' ),
1245 'context' => array( 'view', 'edit' ),
1246 'arg_options' => array(
1247 'sanitize_callback' => 'sanitize_key',
1251 'description' => __( 'Type of Comment for the object.' ),
1253 'context' => array( 'view', 'edit', 'embed' ),
1259 if ( get_option( 'show_avatars' ) ) {
1260 $avatar_properties = array();
1262 $avatar_sizes = rest_get_avatar_sizes();
1263 foreach ( $avatar_sizes as $size ) {
1264 $avatar_properties[ $size ] = array(
1265 /* translators: %d: avatar image size in pixels */
1266 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
1269 'context' => array( 'embed', 'view', 'edit' ),
1273 $schema['properties']['author_avatar_urls'] = array(
1274 'description' => __( 'Avatar URLs for the object author.' ),
1276 'context' => array( 'view', 'edit', 'embed' ),
1278 'properties' => $avatar_properties,
1282 $schema['properties']['meta'] = $this->meta->get_field_schema();
1284 return $this->add_additional_fields_schema( $schema );
1288 * Retrieves the query params for collections.
1293 * @return array Comments collection parameters.
1295 public function get_collection_params() {
1296 $query_params = parent::get_collection_params();
1298 $query_params['context']['default'] = 'view';
1300 $query_params['after'] = array(
1301 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
1303 'format' => 'date-time',
1306 $query_params['author'] = array(
1307 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
1310 'type' => 'integer',
1314 $query_params['author_exclude'] = array(
1315 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
1318 'type' => 'integer',
1322 $query_params['author_email'] = array(
1324 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
1325 'format' => 'email',
1329 $query_params['before'] = array(
1330 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
1332 'format' => 'date-time',
1335 $query_params['exclude'] = array(
1336 'description' => __( 'Ensure result set excludes specific IDs.' ),
1339 'type' => 'integer',
1341 'default' => array(),
1344 $query_params['include'] = array(
1345 'description' => __( 'Limit result set to specific IDs.' ),
1348 'type' => 'integer',
1350 'default' => array(),
1353 $query_params['offset'] = array(
1354 'description' => __( 'Offset the result set by a specific number of items.' ),
1355 'type' => 'integer',
1358 $query_params['order'] = array(
1359 'description' => __( 'Order sort attribute ascending or descending.' ),
1361 'default' => 'desc',
1368 $query_params['orderby'] = array(
1369 'description' => __( 'Sort collection by object attribute.' ),
1371 'default' => 'date_gmt',
1383 $query_params['parent'] = array(
1384 'default' => array(),
1385 'description' => __( 'Limit result set to comments of specific parent IDs.' ),
1388 'type' => 'integer',
1392 $query_params['parent_exclude'] = array(
1393 'default' => array(),
1394 'description' => __( 'Ensure result set excludes specific parent IDs.' ),
1397 'type' => 'integer',
1401 $query_params['post'] = array(
1402 'default' => array(),
1403 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ),
1406 'type' => 'integer',
1410 $query_params['status'] = array(
1411 'default' => 'approve',
1412 'description' => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ),
1413 'sanitize_callback' => 'sanitize_key',
1415 'validate_callback' => 'rest_validate_request_arg',
1418 $query_params['type'] = array(
1419 'default' => 'comment',
1420 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
1421 'sanitize_callback' => 'sanitize_key',
1423 'validate_callback' => 'rest_validate_request_arg',
1426 $query_params['password'] = array(
1427 'description' => __( 'The password for the post if it is password protected.' ),
1432 * Filter collection parameters for the comments controller.
1434 * This filter registers the collection parameter, but does not map the
1435 * collection parameter to an internal WP_Comment_Query parameter. Use the
1436 * `rest_comment_query` filter to set WP_Comment_Query parameters.
1440 * @param array $query_params JSON Schema-formatted collection parameters.
1442 return apply_filters( 'rest_comment_collection_params', $query_params );
1446 * Sets the comment_status of a given comment object when creating or updating a comment.
1451 * @param string|int $new_status New comment status.
1452 * @param int $comment_id Comment ID.
1453 * @return bool Whether the status was changed.
1455 protected function handle_status_param( $new_status, $comment_id ) {
1456 $old_status = wp_get_comment_status( $comment_id );
1458 if ( $new_status === $old_status ) {
1462 switch ( $new_status ) {
1466 $changed = wp_set_comment_status( $comment_id, 'approve' );
1470 $changed = wp_set_comment_status( $comment_id, 'hold' );
1473 $changed = wp_spam_comment( $comment_id );
1476 $changed = wp_unspam_comment( $comment_id );
1479 $changed = wp_trash_comment( $comment_id );
1482 $changed = wp_untrash_comment( $comment_id );
1493 * Checks if the post can be read.
1495 * Correctly handles posts with the inherit status.
1500 * @param WP_Post $post Post object.
1501 * @param WP_REST_Request $request Request data to check.
1502 * @return bool Whether post can be read.
1504 protected function check_read_post_permission( $post, $request ) {
1505 $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
1506 $post_type = get_post_type_object( $post->post_type );
1508 $has_password_filter = false;
1510 // Only check password if a specific post was queried for or a single comment
1511 $requested_post = ! empty( $request['post'] ) && 1 === count( $request['post'] );
1512 $requested_comment = ! empty( $request['id'] );
1513 if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
1514 add_filter( 'post_password_required', '__return_false' );
1516 $has_password_filter = true;
1519 if ( post_password_required( $post ) ) {
1520 $result = current_user_can( $post_type->cap->edit_post, $post->ID );
1522 $result = $posts_controller->check_read_permission( $post );
1525 if ( $has_password_filter ) {
1526 remove_filter( 'post_password_required', '__return_false' );
1533 * Checks if the comment can be read.
1538 * @param WP_Comment $comment Comment object.
1539 * @param WP_REST_Request $request Request data to check.
1540 * @return bool Whether the comment can be read.
1542 protected function check_read_permission( $comment, $request ) {
1543 if ( ! empty( $comment->comment_post_ID ) ) {
1544 $post = get_post( $comment->comment_post_ID );
1546 if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
1552 if ( 0 === get_current_user_id() ) {
1556 if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
1560 if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
1564 return current_user_can( 'edit_comment', $comment->comment_ID );
1568 * Checks if a comment can be edited or deleted.
1573 * @param object $comment Comment object.
1574 * @return bool Whether the comment can be edited or deleted.
1576 protected function check_edit_permission( $comment ) {
1577 if ( 0 === (int) get_current_user_id() ) {
1581 if ( ! current_user_can( 'moderate_comments' ) ) {
1585 return current_user_can( 'edit_comment', $comment->comment_ID );
1589 * Checks a comment author email for validity.
1591 * Accepts either a valid email address or empty string as a valid comment
1592 * author email address. Setting the comment author email to an empty
1593 * string is allowed when a comment is being updated.
1597 * @param string $value Author email value submitted.
1598 * @param WP_REST_Request $request Full details about the request.
1599 * @param string $param The parameter name.
1600 * @return WP_Error|string The sanitized email address, if valid,
1601 * otherwise an error.
1603 public function check_comment_author_email( $value, $request, $param ) {
1604 $email = (string) $value;
1605 if ( empty( $email ) ) {
1609 $check_email = rest_validate_request_arg( $email, $request, $param );
1610 if ( is_wp_error( $check_email ) ) {
1611 return $check_email;