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 ( false === $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 ) && isset( $request['status'] ) ) {
668 // Only the comment status is being changed.
669 $change = $this->handle_status_param( $request['status'], $id );
672 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) );
674 } elseif ( ! empty( $prepared_args ) ) {
675 if ( is_wp_error( $prepared_args ) ) {
676 return $prepared_args;
679 if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) {
680 return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) );
683 $prepared_args['comment_ID'] = $id;
685 $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args );
686 if ( is_wp_error( $check_comment_lengths ) ) {
687 $error_code = $check_comment_lengths->get_error_code();
688 return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) );
691 $updated = wp_update_comment( wp_slash( (array) $prepared_args ) );
693 if ( 0 === $updated ) {
694 return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) );
697 if ( isset( $request['status'] ) ) {
698 $this->handle_status_param( $request['status'], $id );
702 $comment = get_comment( $id );
704 /* This action is documented in lib/endpoints/class-wp-rest-comments-controller.php */
705 do_action( 'rest_insert_comment', $comment, $request, false );
707 $schema = $this->get_item_schema();
709 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
710 $meta_update = $this->meta->update_value( $request['meta'], $id );
712 if ( is_wp_error( $meta_update ) ) {
717 $fields_update = $this->update_additional_fields_for_object( $comment, $request );
719 if ( is_wp_error( $fields_update ) ) {
720 return $fields_update;
723 $request->set_param( 'context', 'edit' );
725 $response = $this->prepare_item_for_response( $comment, $request );
727 return rest_ensure_response( $response );
731 * Checks if a given request has access to delete a comment.
736 * @param WP_REST_Request $request Full details about the request.
737 * @return WP_Error|bool True if the request has access to delete the item, error object otherwise.
739 public function delete_item_permissions_check( $request ) {
740 $id = (int) $request['id'];
741 $comment = get_comment( $id );
744 return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
747 if ( ! $this->check_edit_permission( $comment ) ) {
748 return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) );
759 * @param WP_REST_Request $request Full details about the request.
760 * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
762 public function delete_item( $request ) {
763 $id = (int) $request['id'];
764 $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
766 $comment = get_comment( $id );
768 if ( empty( $comment ) ) {
769 return new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) );
773 * Filters whether a comment can be trashed.
775 * Return false to disable trash support for the post.
779 * @param bool $supports_trash Whether the post type support trashing.
780 * @param WP_Post $comment The comment object being considered for trashing support.
782 $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment );
784 $request->set_param( 'context', 'edit' );
787 $previous = $this->prepare_item_for_response( $comment, $request );
788 $result = wp_delete_comment( $comment->comment_ID, true );
789 $response = new WP_REST_Response();
790 $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
792 // If this type doesn't support trashing, error out.
793 if ( ! $supports_trash ) {
794 return new WP_Error( 'rest_trash_not_supported', __( 'The comment does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
797 if ( 'trash' === $comment->comment_approved ) {
798 return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
801 $result = wp_trash_comment( $comment->comment_ID );
802 $comment = get_comment( $comment->comment_ID );
803 $response = $this->prepare_item_for_response( $comment, $request );
807 return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) );
811 * Fires after a comment is deleted via the REST API.
815 * @param WP_Comment $comment The deleted comment data.
816 * @param WP_REST_Response $response The response returned from the API.
817 * @param WP_REST_Request $request The request sent to the API.
819 do_action( 'rest_delete_comment', $comment, $response, $request );
825 * Prepares a single comment output for response.
830 * @param WP_Comment $comment Comment object.
831 * @param WP_REST_Request $request Request object.
832 * @return WP_REST_Response Response object.
834 public function prepare_item_for_response( $comment, $request ) {
836 'id' => (int) $comment->comment_ID,
837 'post' => (int) $comment->comment_post_ID,
838 'parent' => (int) $comment->comment_parent,
839 'author' => (int) $comment->user_id,
840 'author_name' => $comment->comment_author,
841 'author_email' => $comment->comment_author_email,
842 'author_url' => $comment->comment_author_url,
843 'author_ip' => $comment->comment_author_IP,
844 'author_user_agent' => $comment->comment_agent,
845 'date' => mysql_to_rfc3339( $comment->comment_date ),
846 'date_gmt' => mysql_to_rfc3339( $comment->comment_date_gmt ),
848 /** This filter is documented in wp-includes/comment-template.php */
849 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ),
850 'raw' => $comment->comment_content,
852 'link' => get_comment_link( $comment ),
853 'status' => $this->prepare_status_response( $comment->comment_approved ),
854 'type' => get_comment_type( $comment->comment_ID ),
857 $schema = $this->get_item_schema();
859 if ( ! empty( $schema['properties']['author_avatar_urls'] ) ) {
860 $data['author_avatar_urls'] = rest_get_avatar_urls( $comment->comment_author_email );
863 if ( ! empty( $schema['properties']['meta'] ) ) {
864 $data['meta'] = $this->meta->get_value( $comment->comment_ID, $request );
867 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
868 $data = $this->add_additional_fields_to_object( $data, $request );
869 $data = $this->filter_response_by_context( $data, $context );
871 // Wrap the data in a response object.
872 $response = rest_ensure_response( $data );
874 $response->add_links( $this->prepare_links( $comment ) );
877 * Filters a comment returned from the API.
879 * Allows modification of the comment right before it is returned.
883 * @param WP_REST_Response $response The response object.
884 * @param WP_Comment $comment The original comment object.
885 * @param WP_REST_Request $request Request used to generate the response.
887 return apply_filters( 'rest_prepare_comment', $response, $comment, $request );
891 * Prepares links for the request.
896 * @param WP_Comment $comment Comment object.
897 * @return array Links for the given comment.
899 protected function prepare_links( $comment ) {
902 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ),
904 'collection' => array(
905 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ),
909 if ( 0 !== (int) $comment->user_id ) {
910 $links['author'] = array(
911 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ),
912 'embeddable' => true,
916 if ( 0 !== (int) $comment->comment_post_ID ) {
917 $post = get_post( $comment->comment_post_ID );
919 if ( ! empty( $post->ID ) ) {
920 $obj = get_post_type_object( $post->post_type );
921 $base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
923 $links['up'] = array(
924 'href' => rest_url( 'wp/v2/' . $base . '/' . $comment->comment_post_ID ),
925 'embeddable' => true,
926 'post_type' => $post->post_type,
931 if ( 0 !== (int) $comment->comment_parent ) {
932 $links['in-reply-to'] = array(
933 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ),
934 'embeddable' => true,
938 // Only grab one comment to verify the comment has children.
939 $comment_children = $comment->get_children( array(
944 if ( ! empty( $comment_children ) ) {
946 'parent' => $comment->comment_ID
949 $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) );
951 $links['children'] = array(
960 * Prepends internal property prefix to query parameters to match our response fields.
965 * @param string $query_param Query parameter.
966 * @return string The normalized query parameter.
968 protected function normalize_query_param( $query_param ) {
969 $prefix = 'comment_';
971 switch ( $query_param ) {
973 $normalized = $prefix . 'ID';
976 $normalized = $prefix . 'post_ID';
979 $normalized = $prefix . 'parent';
982 $normalized = 'comment__in';
985 $normalized = $prefix . $query_param;
993 * Checks comment_approved to set comment status for single comment output.
998 * @param string|int $comment_approved comment status.
999 * @return string Comment status.
1001 protected function prepare_status_response( $comment_approved ) {
1003 switch ( $comment_approved ) {
1011 $status = 'approved';
1017 $status = $comment_approved;
1025 * Prepares a single comment to be inserted into the database.
1030 * @param WP_REST_Request $request Request object.
1031 * @return array|WP_Error Prepared comment, otherwise WP_Error object.
1033 protected function prepare_item_for_database( $request ) {
1034 $prepared_comment = array();
1037 * Allow the comment_content to be set via the 'content' or
1038 * the 'content.raw' properties of the Request object.
1040 if ( isset( $request['content'] ) && is_string( $request['content'] ) ) {
1041 $prepared_comment['comment_content'] = $request['content'];
1042 } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) {
1043 $prepared_comment['comment_content'] = $request['content']['raw'];
1046 if ( isset( $request['post'] ) ) {
1047 $prepared_comment['comment_post_ID'] = (int) $request['post'];
1050 if ( isset( $request['parent'] ) ) {
1051 $prepared_comment['comment_parent'] = $request['parent'];
1054 if ( isset( $request['author'] ) ) {
1055 $user = new WP_User( $request['author'] );
1057 if ( $user->exists() ) {
1058 $prepared_comment['user_id'] = $user->ID;
1059 $prepared_comment['comment_author'] = $user->display_name;
1060 $prepared_comment['comment_author_email'] = $user->user_email;
1061 $prepared_comment['comment_author_url'] = $user->user_url;
1063 return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) );
1067 if ( isset( $request['author_name'] ) ) {
1068 $prepared_comment['comment_author'] = $request['author_name'];
1071 if ( isset( $request['author_email'] ) ) {
1072 $prepared_comment['comment_author_email'] = $request['author_email'];
1075 if ( isset( $request['author_url'] ) ) {
1076 $prepared_comment['comment_author_url'] = $request['author_url'];
1079 if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) {
1080 $prepared_comment['comment_author_IP'] = $request['author_ip'];
1081 } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) {
1082 $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
1084 $prepared_comment['comment_author_IP'] = '127.0.0.1';
1087 if ( ! empty( $request['author_user_agent'] ) ) {
1088 $prepared_comment['comment_agent'] = $request['author_user_agent'];
1089 } elseif ( $request->get_header( 'user_agent' ) ) {
1090 $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' );
1093 if ( ! empty( $request['date'] ) ) {
1094 $date_data = rest_get_date_with_gmt( $request['date'] );
1096 if ( ! empty( $date_data ) ) {
1097 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1099 } elseif ( ! empty( $request['date_gmt'] ) ) {
1100 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
1102 if ( ! empty( $date_data ) ) {
1103 list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data;
1108 * Filters a comment after it is prepared for the database.
1110 * Allows modification of the comment right after it is prepared for the database.
1114 * @param array $prepared_comment The prepared comment data for `wp_insert_comment`.
1115 * @param WP_REST_Request $request The current request.
1117 return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request );
1121 * Retrieves the comment's schema, conforming to JSON Schema.
1128 public function get_item_schema() {
1130 '$schema' => 'http://json-schema.org/schema#',
1131 'title' => 'comment',
1133 'properties' => array(
1135 'description' => __( 'Unique identifier for the object.' ),
1136 'type' => 'integer',
1137 'context' => array( 'view', 'edit', 'embed' ),
1141 'description' => __( 'The ID of the user object, if author was a user.' ),
1142 'type' => 'integer',
1143 'context' => array( 'view', 'edit', 'embed' ),
1145 'author_email' => array(
1146 'description' => __( 'Email address for the object author.' ),
1148 'format' => 'email',
1149 'context' => array( 'edit' ),
1150 'arg_options' => array(
1151 'sanitize_callback' => array( $this, 'check_comment_author_email' ),
1152 'validate_callback' => null, // skip built-in validation of 'email'.
1155 'author_ip' => array(
1156 'description' => __( 'IP address for the object author.' ),
1159 'context' => array( 'edit' ),
1161 'author_name' => array(
1162 'description' => __( 'Display name for the object author.' ),
1164 'context' => array( 'view', 'edit', 'embed' ),
1165 'arg_options' => array(
1166 'sanitize_callback' => 'sanitize_text_field',
1169 'author_url' => array(
1170 'description' => __( 'URL for the object author.' ),
1173 'context' => array( 'view', 'edit', 'embed' ),
1175 'author_user_agent' => array(
1176 'description' => __( 'User agent for the object author.' ),
1178 'context' => array( 'edit' ),
1179 'arg_options' => array(
1180 'sanitize_callback' => 'sanitize_text_field',
1184 'description' => __( 'The content for the object.' ),
1186 'context' => array( 'view', 'edit', 'embed' ),
1187 'arg_options' => array(
1188 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1190 'properties' => array(
1192 'description' => __( 'Content for the object, as it exists in the database.' ),
1194 'context' => array( 'edit' ),
1196 'rendered' => array(
1197 'description' => __( 'HTML content for the object, transformed for display.' ),
1199 'context' => array( 'view', 'edit', 'embed' ),
1205 'description' => __( "The date the object was published, in the site's timezone." ),
1207 'format' => 'date-time',
1208 'context' => array( 'view', 'edit', 'embed' ),
1210 'date_gmt' => array(
1211 'description' => __( 'The date the object was published, as GMT.' ),
1213 'format' => 'date-time',
1214 'context' => array( 'view', 'edit' ),
1217 'description' => __( 'URL to the object.' ),
1220 'context' => array( 'view', 'edit', 'embed' ),
1224 'description' => __( 'The ID for the parent of the object.' ),
1225 'type' => 'integer',
1226 'context' => array( 'view', 'edit', 'embed' ),
1230 'description' => __( 'The ID of the associated post object.' ),
1231 'type' => 'integer',
1232 'context' => array( 'view', 'edit' ),
1236 'description' => __( 'State of the object.' ),
1238 'context' => array( 'view', 'edit' ),
1239 'arg_options' => array(
1240 'sanitize_callback' => 'sanitize_key',
1244 'description' => __( 'Type of Comment for the object.' ),
1246 'context' => array( 'view', 'edit', 'embed' ),
1252 if ( get_option( 'show_avatars' ) ) {
1253 $avatar_properties = array();
1255 $avatar_sizes = rest_get_avatar_sizes();
1256 foreach ( $avatar_sizes as $size ) {
1257 $avatar_properties[ $size ] = array(
1258 /* translators: %d: avatar image size in pixels */
1259 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ),
1262 'context' => array( 'embed', 'view', 'edit' ),
1266 $schema['properties']['author_avatar_urls'] = array(
1267 'description' => __( 'Avatar URLs for the object author.' ),
1269 'context' => array( 'view', 'edit', 'embed' ),
1271 'properties' => $avatar_properties,
1275 $schema['properties']['meta'] = $this->meta->get_field_schema();
1277 return $this->add_additional_fields_schema( $schema );
1281 * Retrieves the query params for collections.
1286 * @return array Comments collection parameters.
1288 public function get_collection_params() {
1289 $query_params = parent::get_collection_params();
1291 $query_params['context']['default'] = 'view';
1293 $query_params['after'] = array(
1294 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ),
1296 'format' => 'date-time',
1299 $query_params['author'] = array(
1300 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ),
1303 'type' => 'integer',
1307 $query_params['author_exclude'] = array(
1308 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ),
1311 'type' => 'integer',
1315 $query_params['author_email'] = array(
1317 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ),
1318 'format' => 'email',
1322 $query_params['before'] = array(
1323 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ),
1325 'format' => 'date-time',
1328 $query_params['exclude'] = array(
1329 'description' => __( 'Ensure result set excludes specific IDs.' ),
1332 'type' => 'integer',
1334 'default' => array(),
1337 $query_params['include'] = array(
1338 'description' => __( 'Limit result set to specific IDs.' ),
1341 'type' => 'integer',
1343 'default' => array(),
1346 $query_params['offset'] = array(
1347 'description' => __( 'Offset the result set by a specific number of items.' ),
1348 'type' => 'integer',
1351 $query_params['order'] = array(
1352 'description' => __( 'Order sort attribute ascending or descending.' ),
1354 'default' => 'desc',
1361 $query_params['orderby'] = array(
1362 'description' => __( 'Sort collection by object attribute.' ),
1364 'default' => 'date_gmt',
1376 $query_params['parent'] = array(
1377 'default' => array(),
1378 'description' => __( 'Limit result set to comments of specific parent IDs.' ),
1381 'type' => 'integer',
1385 $query_params['parent_exclude'] = array(
1386 'default' => array(),
1387 'description' => __( 'Ensure result set excludes specific parent IDs.' ),
1390 'type' => 'integer',
1394 $query_params['post'] = array(
1395 'default' => array(),
1396 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ),
1399 'type' => 'integer',
1403 $query_params['status'] = array(
1404 'default' => 'approve',
1405 'description' => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ),
1406 'sanitize_callback' => 'sanitize_key',
1408 'validate_callback' => 'rest_validate_request_arg',
1411 $query_params['type'] = array(
1412 'default' => 'comment',
1413 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ),
1414 'sanitize_callback' => 'sanitize_key',
1416 'validate_callback' => 'rest_validate_request_arg',
1419 $query_params['password'] = array(
1420 'description' => __( 'The password for the post if it is password protected.' ),
1425 * Filter collection parameters for the comments controller.
1427 * This filter registers the collection parameter, but does not map the
1428 * collection parameter to an internal WP_Comment_Query parameter. Use the
1429 * `rest_comment_query` filter to set WP_Comment_Query parameters.
1433 * @param $params JSON Schema-formatted collection parameters.
1435 return apply_filters( 'rest_comment_collection_params', $query_params );
1439 * Sets the comment_status of a given comment object when creating or updating a comment.
1444 * @param string|int $new_status New comment status.
1445 * @param int $comment_id Comment ID.
1446 * @return bool Whether the status was changed.
1448 protected function handle_status_param( $new_status, $comment_id ) {
1449 $old_status = wp_get_comment_status( $comment_id );
1451 if ( $new_status === $old_status ) {
1455 switch ( $new_status ) {
1459 $changed = wp_set_comment_status( $comment_id, 'approve' );
1463 $changed = wp_set_comment_status( $comment_id, 'hold' );
1466 $changed = wp_spam_comment( $comment_id );
1469 $changed = wp_unspam_comment( $comment_id );
1472 $changed = wp_trash_comment( $comment_id );
1475 $changed = wp_untrash_comment( $comment_id );
1486 * Checks if the post can be read.
1488 * Correctly handles posts with the inherit status.
1493 * @param WP_Post $post Post object.
1494 * @param WP_REST_Request $request Request data to check.
1495 * @return bool Whether post can be read.
1497 protected function check_read_post_permission( $post, $request ) {
1498 $posts_controller = new WP_REST_Posts_Controller( $post->post_type );
1499 $post_type = get_post_type_object( $post->post_type );
1501 $has_password_filter = false;
1503 // Only check password if a specific post was queried for or a single comment
1504 $requested_post = ! empty( $request['post'] ) && 1 === count( $request['post'] );
1505 $requested_comment = ! empty( $request['id'] );
1506 if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) {
1507 add_filter( 'post_password_required', '__return_false' );
1509 $has_password_filter = true;
1512 if ( post_password_required( $post ) ) {
1513 $result = current_user_can( $post_type->cap->edit_post, $post->ID );
1515 $result = $posts_controller->check_read_permission( $post );
1518 if ( $has_password_filter ) {
1519 remove_filter( 'post_password_required', '__return_false' );
1526 * Checks if the comment can be read.
1531 * @param WP_Comment $comment Comment object.
1532 * @param WP_REST_Request $request Request data to check.
1533 * @return bool Whether the comment can be read.
1535 protected function check_read_permission( $comment, $request ) {
1536 if ( ! empty( $comment->comment_post_ID ) ) {
1537 $post = get_post( $comment->comment_post_ID );
1539 if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) {
1545 if ( 0 === get_current_user_id() ) {
1549 if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) {
1553 if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) {
1557 return current_user_can( 'edit_comment', $comment->comment_ID );
1561 * Checks if a comment can be edited or deleted.
1566 * @param object $comment Comment object.
1567 * @return bool Whether the comment can be edited or deleted.
1569 protected function check_edit_permission( $comment ) {
1570 if ( 0 === (int) get_current_user_id() ) {
1574 if ( ! current_user_can( 'moderate_comments' ) ) {
1578 return current_user_can( 'edit_comment', $comment->comment_ID );
1582 * Checks a comment author email for validity.
1584 * Accepts either a valid email address or empty string as a valid comment
1585 * author email address. Setting the comment author email to an empty
1586 * string is allowed when a comment is being updated.
1590 * @param string $value Author email value submitted.
1591 * @param WP_REST_Request $request Full details about the request.
1592 * @param string $param The parameter name.
1593 * @return WP_Error|string The sanitized email address, if valid,
1594 * otherwise an error.
1596 public function check_comment_author_email( $value, $request, $param ) {
1597 $email = (string) $value;
1598 if ( empty( $email ) ) {
1602 $check_email = rest_validate_request_arg( $email, $request, $param );
1603 if ( is_wp_error( $check_email ) ) {
1604 return $check_email;