3 * REST API: WP_REST_Posts_Controller class
11 * Core class to access posts via the REST API.
15 * @see WP_REST_Controller
17 class WP_REST_Posts_Controller extends WP_REST_Controller {
29 * Instance of a post meta fields object.
33 * @var WP_REST_Post_Meta_Fields
43 * @param string $post_type Post type.
45 public function __construct( $post_type ) {
46 $this->post_type = $post_type;
47 $this->namespace = 'wp/v2';
48 $obj = get_post_type_object( $post_type );
49 $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
51 $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type );
55 * Registers the routes for the objects of the controller.
60 * @see register_rest_route()
62 public function register_routes() {
64 register_rest_route( $this->namespace, '/' . $this->rest_base, array(
66 'methods' => WP_REST_Server::READABLE,
67 'callback' => array( $this, 'get_items' ),
68 'permission_callback' => array( $this, 'get_items_permissions_check' ),
69 'args' => $this->get_collection_params(),
72 'methods' => WP_REST_Server::CREATABLE,
73 'callback' => array( $this, 'create_item' ),
74 'permission_callback' => array( $this, 'create_item_permissions_check' ),
75 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
77 'schema' => array( $this, 'get_public_item_schema' ),
80 register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
82 'methods' => WP_REST_Server::READABLE,
83 'callback' => array( $this, 'get_item' ),
84 'permission_callback' => array( $this, 'get_item_permissions_check' ),
86 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
88 'description' => __( 'The password for the post if it is password protected.' ),
94 'methods' => WP_REST_Server::EDITABLE,
95 'callback' => array( $this, 'update_item' ),
96 'permission_callback' => array( $this, 'update_item_permissions_check' ),
97 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
100 'methods' => WP_REST_Server::DELETABLE,
101 'callback' => array( $this, 'delete_item' ),
102 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
107 'description' => __( 'Whether to bypass trash and force deletion.' ),
111 'schema' => array( $this, 'get_public_item_schema' ),
116 * Checks if a given request has access to read posts.
121 * @param WP_REST_Request $request Full details about the request.
122 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
124 public function get_items_permissions_check( $request ) {
126 $post_type = get_post_type_object( $this->post_type );
128 if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
129 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
136 * Retrieves a collection of posts.
141 * @param WP_REST_Request $request Full details about the request.
142 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
144 public function get_items( $request ) {
146 // Ensure a search string is set in case the orderby is set to 'relevance'.
147 if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
148 return new WP_Error( 'rest_no_search_term_defined', __( 'You need to define a search term to order by relevance.' ), array( 'status' => 400 ) );
151 // Ensure an include parameter is set in case the orderby is set to 'include'.
152 if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
153 return new WP_Error( 'rest_orderby_include_missing_include', sprintf( __( 'Missing parameter(s): %s' ), 'include' ), array( 'status' => 400 ) );
156 // Retrieve the list of registered collection query parameters.
157 $registered = $this->get_collection_params();
161 * This array defines mappings between public API query parameters whose
162 * values are accepted as-passed, and their internal WP_Query parameter
163 * name equivalents (some are the same). Only values which are also
164 * present in $registered will be set.
166 $parameter_mappings = array(
167 'author' => 'author__in',
168 'author_exclude' => 'author__not_in',
169 'exclude' => 'post__not_in',
170 'include' => 'post__in',
171 'menu_order' => 'menu_order',
172 'offset' => 'offset',
174 'orderby' => 'orderby',
176 'parent' => 'post_parent__in',
177 'parent_exclude' => 'post_parent__not_in',
179 'slug' => 'post_name__in',
180 'status' => 'post_status',
184 * For each known parameter which is both registered and present in the request,
185 * set the parameter's value on the query $args.
187 foreach ( $parameter_mappings as $api_param => $wp_param ) {
188 if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
189 $args[ $wp_param ] = $request[ $api_param ];
193 // Check for & assign any parameters which require special handling or setting.
194 $args['date_query'] = array();
196 // Set before into date query. Date query must be specified as an array of an array.
197 if ( isset( $registered['before'], $request['before'] ) ) {
198 $args['date_query'][0]['before'] = $request['before'];
201 // Set after into date query. Date query must be specified as an array of an array.
202 if ( isset( $registered['after'], $request['after'] ) ) {
203 $args['date_query'][0]['after'] = $request['after'];
206 // Ensure our per_page parameter overrides any provided posts_per_page filter.
207 if ( isset( $registered['per_page'] ) ) {
208 $args['posts_per_page'] = $request['per_page'];
211 if ( isset( $registered['sticky'], $request['sticky'] ) ) {
212 $sticky_posts = get_option( 'sticky_posts', array() );
213 if ( $sticky_posts && $request['sticky'] ) {
215 * As post__in will be used to only get sticky posts,
216 * we have to support the case where post__in was already
219 $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
222 * If we intersected, but there are no post ids in common,
223 * WP_Query won't return "no posts" for post__in = array()
224 * so we have to fake it a bit.
226 if ( ! $args['post__in'] ) {
227 $args['post__in'] = array( -1 );
229 } elseif ( $sticky_posts ) {
231 * As post___not_in will be used to only get posts that
232 * are not sticky, we have to support the case where post__not_in
233 * was already specified.
235 $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
239 // Force the post_type argument, since it's not a user input variable.
240 $args['post_type'] = $this->post_type;
243 * Filters the query arguments for a request.
245 * Enables adding extra arguments or setting defaults for a post collection request.
249 * @link https://developer.wordpress.org/reference/classes/wp_query/
251 * @param array $args Key value array of query var to query value.
252 * @param WP_REST_Request $request The request used.
254 $args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
255 $query_args = $this->prepare_items_query( $args, $request );
257 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
259 foreach ( $taxonomies as $taxonomy ) {
260 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
261 $tax_exclude = $base . '_exclude';
263 if ( ! empty( $request[ $base ] ) ) {
264 $query_args['tax_query'][] = array(
265 'taxonomy' => $taxonomy->name,
266 'field' => 'term_id',
267 'terms' => $request[ $base ],
268 'include_children' => false,
272 if ( ! empty( $request[ $tax_exclude ] ) ) {
273 $query_args['tax_query'][] = array(
274 'taxonomy' => $taxonomy->name,
275 'field' => 'term_id',
276 'terms' => $request[ $tax_exclude ],
277 'include_children' => false,
278 'operator' => 'NOT IN',
283 $posts_query = new WP_Query();
284 $query_result = $posts_query->query( $query_args );
286 // Allow access to all password protected posts if the context is edit.
287 if ( 'edit' === $request['context'] ) {
288 add_filter( 'post_password_required', '__return_false' );
293 foreach ( $query_result as $post ) {
294 if ( ! $this->check_read_permission( $post ) ) {
298 $data = $this->prepare_item_for_response( $post, $request );
299 $posts[] = $this->prepare_response_for_collection( $data );
303 if ( 'edit' === $request['context'] ) {
304 remove_filter( 'post_password_required', '__return_false' );
307 $page = (int) $query_args['paged'];
308 $total_posts = $posts_query->found_posts;
310 if ( $total_posts < 1 ) {
311 // Out-of-bounds, run the query again without LIMIT for total count.
312 unset( $query_args['paged'] );
314 $count_query = new WP_Query();
315 $count_query->query( $query_args );
316 $total_posts = $count_query->found_posts;
319 $max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
320 $response = rest_ensure_response( $posts );
322 $response->header( 'X-WP-Total', (int) $total_posts );
323 $response->header( 'X-WP-TotalPages', (int) $max_pages );
325 $request_params = $request->get_query_params();
326 $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
329 $prev_page = $page - 1;
331 if ( $prev_page > $max_pages ) {
332 $prev_page = $max_pages;
335 $prev_link = add_query_arg( 'page', $prev_page, $base );
336 $response->link_header( 'prev', $prev_link );
338 if ( $max_pages > $page ) {
339 $next_page = $page + 1;
340 $next_link = add_query_arg( 'page', $next_page, $base );
342 $response->link_header( 'next', $next_link );
349 * Checks if a given request has access to read a post.
354 * @param WP_REST_Request $request Full details about the request.
355 * @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise.
357 public function get_item_permissions_check( $request ) {
359 $post = get_post( (int) $request['id'] );
361 if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
362 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
365 if ( $post && ! empty( $request['password'] ) ) {
366 // Check post password, and return error if invalid.
367 if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
368 return new WP_Error( 'rest_post_incorrect_password', __( 'Incorrect post password.' ), array( 'status' => 403 ) );
372 // Allow access to all password protected posts if the context is edit.
373 if ( 'edit' === $request['context'] ) {
374 add_filter( 'post_password_required', '__return_false' );
378 return $this->check_read_permission( $post );
385 * Checks if the user can access password-protected content.
387 * This method determines whether we need to override the regular password
388 * check in core with a filter.
393 * @param WP_Post $post Post to check against.
394 * @param WP_REST_Request $request Request data to check.
395 * @return bool True if the user can access password-protected content, otherwise false.
397 public function can_access_password_content( $post, $request ) {
398 if ( empty( $post->post_password ) ) {
399 // No filter required.
403 // Edit context always gets access to password-protected posts.
404 if ( 'edit' === $request['context'] ) {
408 // No password, no auth.
409 if ( empty( $request['password'] ) ) {
413 // Double-check the request password.
414 return hash_equals( $post->post_password, $request['password'] );
418 * Retrieves a single post.
423 * @param WP_REST_Request $request Full details about the request.
424 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
426 public function get_item( $request ) {
427 $id = (int) $request['id'];
428 $post = get_post( $id );
430 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
431 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
434 $data = $this->prepare_item_for_response( $post, $request );
435 $response = rest_ensure_response( $data );
437 if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) {
438 $response->link_header( 'alternate', get_permalink( $id ), array( 'type' => 'text/html' ) );
445 * Checks if a given request has access to create a post.
450 * @param WP_REST_Request $request Full details about the request.
451 * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
453 public function create_item_permissions_check( $request ) {
455 $post_type = get_post_type_object( $this->post_type );
457 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
458 return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
461 if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
462 return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
465 if ( ! current_user_can( $post_type->cap->create_posts ) ) {
466 return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
469 if ( ! $this->check_assign_terms_permission( $request ) ) {
470 return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
477 * Creates a single post.
482 * @param WP_REST_Request $request Full details about the request.
483 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
485 public function create_item( $request ) {
486 if ( ! empty( $request['id'] ) ) {
487 return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
490 $prepared_post = $this->prepare_item_for_database( $request );
492 if ( is_wp_error( $prepared_post ) ) {
493 return $prepared_post;
496 $prepared_post->post_type = $this->post_type;
498 $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true );
500 if ( is_wp_error( $post_id ) ) {
502 if ( 'db_insert_error' === $post_id->get_error_code() ) {
503 $post_id->add_data( array( 'status' => 500 ) );
505 $post_id->add_data( array( 'status' => 400 ) );
511 $post = get_post( $post_id );
514 * Fires after a single post is created or updated via the REST API.
516 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
520 * @param WP_Post $post Inserted or updated post object.
521 * @param WP_REST_Request $request Request object.
522 * @param bool $creating True when creating a post, false when updating.
524 do_action( "rest_insert_{$this->post_type}", $post, $request, true );
526 $schema = $this->get_item_schema();
528 if ( ! empty( $schema['properties']['sticky'] ) ) {
529 if ( ! empty( $request['sticky'] ) ) {
530 stick_post( $post_id );
532 unstick_post( $post_id );
536 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
537 $this->handle_featured_media( $request['featured_media'], $post_id );
540 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
541 set_post_format( $post, $request['format'] );
544 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
545 $this->handle_template( $request['template'], $post_id );
548 $terms_update = $this->handle_terms( $post_id, $request );
550 if ( is_wp_error( $terms_update ) ) {
551 return $terms_update;
554 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
555 $meta_update = $this->meta->update_value( $request['meta'], $post_id );
557 if ( is_wp_error( $meta_update ) ) {
562 $post = get_post( $post_id );
563 $fields_update = $this->update_additional_fields_for_object( $post, $request );
565 if ( is_wp_error( $fields_update ) ) {
566 return $fields_update;
569 $request->set_param( 'context', 'edit' );
571 $response = $this->prepare_item_for_response( $post, $request );
572 $response = rest_ensure_response( $response );
574 $response->set_status( 201 );
575 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $post_id ) ) );
581 * Checks if a given request has access to update a post.
586 * @param WP_REST_Request $request Full details about the request.
587 * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
589 public function update_item_permissions_check( $request ) {
591 $post = get_post( $request['id'] );
592 $post_type = get_post_type_object( $this->post_type );
594 if ( $post && ! $this->check_update_permission( $post ) ) {
595 return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
598 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
599 return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to update posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
602 if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
603 return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
606 if ( ! $this->check_assign_terms_permission( $request ) ) {
607 return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
614 * Updates a single post.
619 * @param WP_REST_Request $request Full details about the request.
620 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
622 public function update_item( $request ) {
623 $id = (int) $request['id'];
624 $post = get_post( $id );
626 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
627 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
630 $post = $this->prepare_item_for_database( $request );
632 if ( is_wp_error( $post ) ) {
636 // convert the post object to an array, otherwise wp_update_post will expect non-escaped input.
637 $post_id = wp_update_post( wp_slash( (array) $post ), true );
639 if ( is_wp_error( $post_id ) ) {
640 if ( 'db_update_error' === $post_id->get_error_code() ) {
641 $post_id->add_data( array( 'status' => 500 ) );
643 $post_id->add_data( array( 'status' => 400 ) );
648 $post = get_post( $post_id );
650 /* This action is documented in lib/endpoints/class-wp-rest-controller.php */
651 do_action( "rest_insert_{$this->post_type}", $post, $request, false );
653 $schema = $this->get_item_schema();
655 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
656 set_post_format( $post, $request['format'] );
659 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
660 $this->handle_featured_media( $request['featured_media'], $post_id );
663 if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) {
664 if ( ! empty( $request['sticky'] ) ) {
665 stick_post( $post_id );
667 unstick_post( $post_id );
671 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
672 $this->handle_template( $request['template'], $post->ID );
675 $terms_update = $this->handle_terms( $post->ID, $request );
677 if ( is_wp_error( $terms_update ) ) {
678 return $terms_update;
681 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
682 $meta_update = $this->meta->update_value( $request['meta'], $post->ID );
684 if ( is_wp_error( $meta_update ) ) {
689 $post = get_post( $post_id );
690 $fields_update = $this->update_additional_fields_for_object( $post, $request );
692 if ( is_wp_error( $fields_update ) ) {
693 return $fields_update;
696 $request->set_param( 'context', 'edit' );
698 $response = $this->prepare_item_for_response( $post, $request );
700 return rest_ensure_response( $response );
704 * Checks if a given request has access to delete a post.
709 * @param WP_REST_Request $request Full details about the request.
710 * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
712 public function delete_item_permissions_check( $request ) {
714 $post = get_post( $request['id'] );
716 if ( $post && ! $this->check_delete_permission( $post ) ) {
717 return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
724 * Deletes a single post.
729 * @param WP_REST_Request $request Full details about the request.
730 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
732 public function delete_item( $request ) {
733 $id = (int) $request['id'];
734 $force = (bool) $request['force'];
736 $post = get_post( $id );
738 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
739 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
742 $supports_trash = ( EMPTY_TRASH_DAYS > 0 );
744 if ( 'attachment' === $post->post_type ) {
745 $supports_trash = $supports_trash && MEDIA_TRASH;
749 * Filters whether a post is trashable.
751 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
753 * Pass false to disable trash support for the post.
757 * @param bool $supports_trash Whether the post type support trashing.
758 * @param WP_Post $post The Post object being considered for trashing support.
760 $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );
762 if ( ! $this->check_delete_permission( $post ) ) {
763 return new WP_Error( 'rest_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
766 $request->set_param( 'context', 'edit' );
769 // If we're forcing, then delete permanently.
771 $previous = $this->prepare_item_for_response( $post, $request );
772 $result = wp_delete_post( $id, true );
773 $response = new WP_REST_Response();
774 $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
776 // If we don't support trashing for this type, error out.
777 if ( ! $supports_trash ) {
778 return new WP_Error( 'rest_trash_not_supported', __( 'The post does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
781 // Otherwise, only trash if we haven't already.
782 if ( 'trash' === $post->post_status ) {
783 return new WP_Error( 'rest_already_trashed', __( 'The post has already been deleted.' ), array( 'status' => 410 ) );
786 // (Note that internally this falls through to `wp_delete_post` if
787 // the trash is disabled.)
788 $result = wp_trash_post( $id );
789 $post = get_post( $id );
790 $response = $this->prepare_item_for_response( $post, $request );
794 return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
798 * Fires immediately after a single post is deleted or trashed via the REST API.
800 * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
804 * @param object $post The deleted or trashed post.
805 * @param WP_REST_Response $response The response data.
806 * @param WP_REST_Request $request The request sent to the API.
808 do_action( "rest_delete_{$this->post_type}", $post, $response, $request );
814 * Determines the allowed query_vars for a get_items() response and prepares
820 * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
821 * @param WP_REST_Request $request Optional. Full details about the request.
822 * @return array Items query arguments.
824 protected function prepare_items_query( $prepared_args = array(), $request = null ) {
825 $query_args = array();
827 foreach ( $prepared_args as $key => $value ) {
829 * Filters the query_vars used in get_items() for the constructed query.
831 * The dynamic portion of the hook name, `$key`, refers to the query_var key.
835 * @param string $value The query_var value.
837 $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value );
840 if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
841 $query_args['ignore_sticky_posts'] = true;
844 // Map to proper WP_Query orderby param.
845 if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
846 $orderby_mappings = array(
848 'include' => 'post__in',
849 'slug' => 'post_name',
852 if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
853 $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
861 * Checks the post_date_gmt or modified_gmt and prepare any post or
862 * modified date for single post output.
867 * @param string $date_gmt GMT publication time.
868 * @param string|null $date Optional. Local publication time. Default null.
869 * @return string|null ISO8601/RFC3339 formatted datetime.
871 protected function prepare_date_response( $date_gmt, $date = null ) {
872 // Use the date if passed.
873 if ( isset( $date ) ) {
874 return mysql_to_rfc3339( $date );
877 // Return null if $date_gmt is empty/zeros.
878 if ( '0000-00-00 00:00:00' === $date_gmt ) {
882 // Return the formatted datetime.
883 return mysql_to_rfc3339( $date_gmt );
887 * Prepares a single post for create or update.
892 * @param WP_REST_Request $request Request object.
893 * @return stdClass|WP_Error Post object or WP_Error.
895 protected function prepare_item_for_database( $request ) {
896 $prepared_post = new stdClass;
899 if ( isset( $request['id'] ) ) {
900 $prepared_post->ID = absint( $request['id'] );
903 $schema = $this->get_item_schema();
906 if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
907 if ( is_string( $request['title'] ) ) {
908 $prepared_post->post_title = $request['title'];
909 } elseif ( ! empty( $request['title']['raw'] ) ) {
910 $prepared_post->post_title = $request['title']['raw'];
915 if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) {
916 if ( is_string( $request['content'] ) ) {
917 $prepared_post->post_content = $request['content'];
918 } elseif ( isset( $request['content']['raw'] ) ) {
919 $prepared_post->post_content = $request['content']['raw'];
924 if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) {
925 if ( is_string( $request['excerpt'] ) ) {
926 $prepared_post->post_excerpt = $request['excerpt'];
927 } elseif ( isset( $request['excerpt']['raw'] ) ) {
928 $prepared_post->post_excerpt = $request['excerpt']['raw'];
933 if ( empty( $request['id'] ) ) {
934 // Creating new post, use default type for the controller.
935 $prepared_post->post_type = $this->post_type;
937 // Updating a post, use previous type.
938 $prepared_post->post_type = get_post_type( $request['id'] );
941 $post_type = get_post_type_object( $prepared_post->post_type );
944 if ( ! empty( $schema['properties']['status'] ) && isset( $request['status'] ) ) {
945 $status = $this->handle_status_param( $request['status'], $post_type );
947 if ( is_wp_error( $status ) ) {
951 $prepared_post->post_status = $status;
955 if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) {
956 $date_data = rest_get_date_with_gmt( $request['date'] );
958 if ( ! empty( $date_data ) ) {
959 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
961 } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) {
962 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
964 if ( ! empty( $date_data ) ) {
965 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
970 if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) {
971 $prepared_post->post_name = $request['slug'];
975 if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) {
976 $post_author = (int) $request['author'];
978 if ( get_current_user_id() !== $post_author ) {
979 $user_obj = get_userdata( $post_author );
982 return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) );
986 $prepared_post->post_author = $post_author;
990 if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) {
991 $prepared_post->post_password = $request['password'];
993 if ( '' !== $request['password'] ) {
994 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
995 return new WP_Error( 'rest_invalid_field', __( 'A post can not be sticky and have a password.' ), array( 'status' => 400 ) );
998 if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) {
999 return new WP_Error( 'rest_invalid_field', __( 'A sticky post can not be password protected.' ), array( 'status' => 400 ) );
1004 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
1005 if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) {
1006 return new WP_Error( 'rest_invalid_field', __( 'A password protected post can not be set to sticky.' ), array( 'status' => 400 ) );
1011 if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) {
1012 if ( 0 === (int) $request['parent'] ) {
1013 $prepared_post->post_parent = 0;
1015 $parent = get_post( (int) $request['parent'] );
1016 if ( empty( $parent ) ) {
1017 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) );
1019 $prepared_post->post_parent = (int) $parent->ID;
1024 if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) {
1025 $prepared_post->menu_order = (int) $request['menu_order'];
1029 if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) {
1030 $prepared_post->comment_status = $request['comment_status'];
1034 if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) {
1035 $prepared_post->ping_status = $request['ping_status'];
1039 * Filters a post before it is inserted via the REST API.
1041 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1045 * @param stdClass $prepared_post An object representing a single post prepared
1046 * for inserting or updating the database.
1047 * @param WP_REST_Request $request Request object.
1049 return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );
1054 * Determines validity and normalizes the given status parameter.
1059 * @param string $post_status Post status.
1060 * @param object $post_type Post type.
1061 * @return string|WP_Error Post status or WP_Error if lacking the proper permission.
1063 protected function handle_status_param( $post_status, $post_type ) {
1065 switch ( $post_status ) {
1070 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1071 return new WP_Error( 'rest_cannot_publish', __( 'Sorry, you are not allowed to create private posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
1076 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1077 return new WP_Error( 'rest_cannot_publish', __( 'Sorry, you are not allowed to publish posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
1081 if ( ! get_post_status_object( $post_status ) ) {
1082 $post_status = 'draft';
1087 return $post_status;
1091 * Determines the featured media based on a request param.
1096 * @param int $featured_media Featured Media ID.
1097 * @param int $post_id Post ID.
1098 * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
1100 protected function handle_featured_media( $featured_media, $post_id ) {
1102 $featured_media = (int) $featured_media;
1103 if ( $featured_media ) {
1104 $result = set_post_thumbnail( $post_id, $featured_media );
1108 return new WP_Error( 'rest_invalid_featured_media', __( 'Invalid featured media ID.' ), array( 'status' => 400 ) );
1111 return delete_post_thumbnail( $post_id );
1117 * Sets the template for a post.
1122 * @param string $template Page template filename.
1123 * @param integer $post_id Post ID.
1125 public function handle_template( $template, $post_id ) {
1126 if ( in_array( $template, array_keys( wp_get_theme()->get_page_templates( get_post( $post_id ) ) ), true ) ) {
1127 update_post_meta( $post_id, '_wp_page_template', $template );
1129 update_post_meta( $post_id, '_wp_page_template', '' );
1134 * Updates the post's terms from a REST request.
1139 * @param int $post_id The post ID to update the terms form.
1140 * @param WP_REST_Request $request The request object with post and terms data.
1141 * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null.
1143 protected function handle_terms( $post_id, $request ) {
1144 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1146 foreach ( $taxonomies as $taxonomy ) {
1147 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1149 if ( ! isset( $request[ $base ] ) ) {
1153 $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name );
1155 if ( is_wp_error( $result ) ) {
1162 * Checks whether current user can assign all terms sent with the current request.
1166 * @param WP_REST_Request $request The request object with post and terms data.
1167 * @return bool Whether the current user can assign the provided terms.
1169 protected function check_assign_terms_permission( $request ) {
1170 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1171 foreach ( $taxonomies as $taxonomy ) {
1172 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1174 if ( ! isset( $request[ $base ] ) ) {
1178 foreach ( $request[ $base ] as $term_id ) {
1179 // Invalid terms will be rejected later.
1180 if ( ! get_term( $term_id, $taxonomy->name ) ) {
1184 if ( ! current_user_can( 'assign_term', (int) $term_id ) ) {
1194 * Checks if a given post type can be viewed or managed.
1199 * @param object|string $post_type Post type name or object.
1200 * @return bool Whether the post type is allowed in REST.
1202 protected function check_is_post_type_allowed( $post_type ) {
1203 if ( ! is_object( $post_type ) ) {
1204 $post_type = get_post_type_object( $post_type );
1207 if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) {
1215 * Checks if a post can be read.
1217 * Correctly handles posts with the inherit status.
1222 * @param object $post Post object.
1223 * @return bool Whether the post can be read.
1225 public function check_read_permission( $post ) {
1226 $post_type = get_post_type_object( $post->post_type );
1227 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1231 // Is the post readable?
1232 if ( 'publish' === $post->post_status || current_user_can( $post_type->cap->read_post, $post->ID ) ) {
1236 $post_status_obj = get_post_status_object( $post->post_status );
1237 if ( $post_status_obj && $post_status_obj->public ) {
1241 // Can we read the parent if we're inheriting?
1242 if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
1243 $parent = get_post( $post->post_parent );
1244 return $this->check_read_permission( $parent );
1248 * If there isn't a parent, but the status is set to inherit, assume
1249 * it's published (as per get_post_status()).
1251 if ( 'inherit' === $post->post_status ) {
1259 * Checks if a post can be edited.
1264 * @param object $post Post object.
1265 * @return bool Whether the post can be edited.
1267 protected function check_update_permission( $post ) {
1268 $post_type = get_post_type_object( $post->post_type );
1270 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1274 return current_user_can( $post_type->cap->edit_post, $post->ID );
1278 * Checks if a post can be created.
1283 * @param object $post Post object.
1284 * @return bool Whether the post can be created.
1286 protected function check_create_permission( $post ) {
1287 $post_type = get_post_type_object( $post->post_type );
1289 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1293 return current_user_can( $post_type->cap->create_posts );
1297 * Checks if a post can be deleted.
1302 * @param object $post Post object.
1303 * @return bool Whether the post can be deleted.
1305 protected function check_delete_permission( $post ) {
1306 $post_type = get_post_type_object( $post->post_type );
1308 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1312 return current_user_can( $post_type->cap->delete_post, $post->ID );
1316 * Prepares a single post output for response.
1321 * @param WP_Post $post Post object.
1322 * @param WP_REST_Request $request Request object.
1323 * @return WP_REST_Response Response object.
1325 public function prepare_item_for_response( $post, $request ) {
1326 $GLOBALS['post'] = $post;
1328 setup_postdata( $post );
1330 $schema = $this->get_item_schema();
1332 // Base fields for every post.
1335 if ( ! empty( $schema['properties']['id'] ) ) {
1336 $data['id'] = $post->ID;
1339 if ( ! empty( $schema['properties']['date'] ) ) {
1340 $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
1343 if ( ! empty( $schema['properties']['date_gmt'] ) ) {
1344 $data['date_gmt'] = $this->prepare_date_response( $post->post_date_gmt );
1347 if ( ! empty( $schema['properties']['guid'] ) ) {
1348 $data['guid'] = array(
1349 /** This filter is documented in wp-includes/post-template.php */
1350 'rendered' => apply_filters( 'get_the_guid', $post->guid ),
1351 'raw' => $post->guid,
1355 if ( ! empty( $schema['properties']['modified'] ) ) {
1356 $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
1359 if ( ! empty( $schema['properties']['modified_gmt'] ) ) {
1360 $data['modified_gmt'] = $this->prepare_date_response( $post->post_modified_gmt );
1363 if ( ! empty( $schema['properties']['password'] ) ) {
1364 $data['password'] = $post->post_password;
1367 if ( ! empty( $schema['properties']['slug'] ) ) {
1368 $data['slug'] = $post->post_name;
1371 if ( ! empty( $schema['properties']['status'] ) ) {
1372 $data['status'] = $post->post_status;
1375 if ( ! empty( $schema['properties']['type'] ) ) {
1376 $data['type'] = $post->post_type;
1379 if ( ! empty( $schema['properties']['link'] ) ) {
1380 $data['link'] = get_permalink( $post->ID );
1383 if ( ! empty( $schema['properties']['title'] ) ) {
1384 add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1386 $data['title'] = array(
1387 'raw' => $post->post_title,
1388 'rendered' => get_the_title( $post->ID ),
1391 remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1394 $has_password_filter = false;
1396 if ( $this->can_access_password_content( $post, $request ) ) {
1397 // Allow access to the post, permissions already checked before.
1398 add_filter( 'post_password_required', '__return_false' );
1400 $has_password_filter = true;
1403 if ( ! empty( $schema['properties']['content'] ) ) {
1404 $data['content'] = array(
1405 'raw' => $post->post_content,
1406 /** This filter is documented in wp-includes/post-template.php */
1407 'rendered' => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
1408 'protected' => (bool) $post->post_password,
1412 if ( ! empty( $schema['properties']['excerpt'] ) ) {
1413 /** This filter is documented in wp-includes/post-template.php */
1414 $excerpt = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
1415 $data['excerpt'] = array(
1416 'raw' => $post->post_excerpt,
1417 'rendered' => post_password_required( $post ) ? '' : $excerpt,
1418 'protected' => (bool) $post->post_password,
1422 if ( $has_password_filter ) {
1424 remove_filter( 'post_password_required', '__return_false' );
1427 if ( ! empty( $schema['properties']['author'] ) ) {
1428 $data['author'] = (int) $post->post_author;
1431 if ( ! empty( $schema['properties']['featured_media'] ) ) {
1432 $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID );
1435 if ( ! empty( $schema['properties']['parent'] ) ) {
1436 $data['parent'] = (int) $post->post_parent;
1439 if ( ! empty( $schema['properties']['menu_order'] ) ) {
1440 $data['menu_order'] = (int) $post->menu_order;
1443 if ( ! empty( $schema['properties']['comment_status'] ) ) {
1444 $data['comment_status'] = $post->comment_status;
1447 if ( ! empty( $schema['properties']['ping_status'] ) ) {
1448 $data['ping_status'] = $post->ping_status;
1451 if ( ! empty( $schema['properties']['sticky'] ) ) {
1452 $data['sticky'] = is_sticky( $post->ID );
1455 if ( ! empty( $schema['properties']['template'] ) ) {
1456 if ( $template = get_page_template_slug( $post->ID ) ) {
1457 $data['template'] = $template;
1459 $data['template'] = '';
1463 if ( ! empty( $schema['properties']['format'] ) ) {
1464 $data['format'] = get_post_format( $post->ID );
1466 // Fill in blank post format.
1467 if ( empty( $data['format'] ) ) {
1468 $data['format'] = 'standard';
1472 if ( ! empty( $schema['properties']['meta'] ) ) {
1473 $data['meta'] = $this->meta->get_value( $post->ID, $request );
1476 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1478 foreach ( $taxonomies as $taxonomy ) {
1479 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1481 if ( ! empty( $schema['properties'][ $base ] ) ) {
1482 $terms = get_the_terms( $post, $taxonomy->name );
1483 $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
1487 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1488 $data = $this->add_additional_fields_to_object( $data, $request );
1489 $data = $this->filter_response_by_context( $data, $context );
1491 // Wrap the data in a response object.
1492 $response = rest_ensure_response( $data );
1494 $response->add_links( $this->prepare_links( $post ) );
1497 * Filters the post data for a response.
1499 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1503 * @param WP_REST_Response $response The response object.
1504 * @param WP_Post $post Post object.
1505 * @param WP_REST_Request $request Request object.
1507 return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
1511 * Overwrites the default protected title format.
1513 * By default, WordPress will show password protected posts with a title of
1514 * "Protected: %s", as the REST API communicates the protected status of a post
1515 * in a machine readable format, we remove the "Protected: " prefix.
1517 * @return string Protected title format.
1519 public function protected_title_format() {
1524 * Prepares links for the request.
1529 * @param WP_Post $post Post object.
1530 * @return array Links for the given post.
1532 protected function prepare_links( $post ) {
1533 $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
1538 'href' => rest_url( trailingslashit( $base ) . $post->ID ),
1540 'collection' => array(
1541 'href' => rest_url( $base ),
1544 'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
1548 if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
1549 && ! empty( $post->post_author ) ) {
1550 $links['author'] = array(
1551 'href' => rest_url( 'wp/v2/users/' . $post->post_author ),
1552 'embeddable' => true,
1556 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
1557 $replies_url = rest_url( 'wp/v2/comments' );
1558 $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
1560 $links['replies'] = array(
1561 'href' => $replies_url,
1562 'embeddable' => true,
1566 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
1567 $links['version-history'] = array(
1568 'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions' ),
1572 $post_type_obj = get_post_type_object( $post->post_type );
1574 if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
1575 $links['up'] = array(
1576 'href' => rest_url( trailingslashit( $base ) . (int) $post->post_parent ),
1577 'embeddable' => true,
1581 // If we have a featured media, add that.
1582 if ( $featured_media = get_post_thumbnail_id( $post->ID ) ) {
1583 $image_url = rest_url( 'wp/v2/media/' . $featured_media );
1585 $links['https://api.w.org/featuredmedia'] = array(
1586 'href' => $image_url,
1587 'embeddable' => true,
1591 if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
1592 $attachments_url = rest_url( 'wp/v2/media' );
1593 $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
1595 $links['https://api.w.org/attachment'] = array(
1596 'href' => $attachments_url,
1600 $taxonomies = get_object_taxonomies( $post->post_type );
1602 if ( ! empty( $taxonomies ) ) {
1603 $links['https://api.w.org/term'] = array();
1605 foreach ( $taxonomies as $tax ) {
1606 $taxonomy_obj = get_taxonomy( $tax );
1608 // Skip taxonomies that are not public.
1609 if ( empty( $taxonomy_obj->show_in_rest ) ) {
1613 $tax_base = ! empty( $taxonomy_obj->rest_base ) ? $taxonomy_obj->rest_base : $tax;
1615 $terms_url = add_query_arg(
1618 rest_url( 'wp/v2/' . $tax_base )
1621 $links['https://api.w.org/term'][] = array(
1622 'href' => $terms_url,
1624 'embeddable' => true,
1633 * Retrieves the post's schema, conforming to JSON Schema.
1638 * @return array Item schema data.
1640 public function get_item_schema() {
1643 '$schema' => 'http://json-schema.org/schema#',
1644 'title' => $this->post_type,
1646 // Base properties for every Post.
1647 'properties' => array(
1649 'description' => __( "The date the object was published, in the site's timezone." ),
1651 'format' => 'date-time',
1652 'context' => array( 'view', 'edit', 'embed' ),
1654 'date_gmt' => array(
1655 'description' => __( 'The date the object was published, as GMT.' ),
1657 'format' => 'date-time',
1658 'context' => array( 'view', 'edit' ),
1661 'description' => __( 'The globally unique identifier for the object.' ),
1663 'context' => array( 'view', 'edit' ),
1665 'properties' => array(
1667 'description' => __( 'GUID for the object, as it exists in the database.' ),
1669 'context' => array( 'edit' ),
1672 'rendered' => array(
1673 'description' => __( 'GUID for the object, transformed for display.' ),
1675 'context' => array( 'view', 'edit' ),
1681 'description' => __( 'Unique identifier for the object.' ),
1682 'type' => 'integer',
1683 'context' => array( 'view', 'edit', 'embed' ),
1687 'description' => __( 'URL to the object.' ),
1690 'context' => array( 'view', 'edit', 'embed' ),
1693 'modified' => array(
1694 'description' => __( "The date the object was last modified, in the site's timezone." ),
1696 'format' => 'date-time',
1697 'context' => array( 'view', 'edit' ),
1700 'modified_gmt' => array(
1701 'description' => __( 'The date the object was last modified, as GMT.' ),
1703 'format' => 'date-time',
1704 'context' => array( 'view', 'edit' ),
1708 'description' => __( 'An alphanumeric identifier for the object unique to its type.' ),
1710 'context' => array( 'view', 'edit', 'embed' ),
1711 'arg_options' => array(
1712 'sanitize_callback' => array( $this, 'sanitize_slug' ),
1716 'description' => __( 'A named status for the object.' ),
1718 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ),
1719 'context' => array( 'edit' ),
1722 'description' => __( 'Type of Post for the object.' ),
1724 'context' => array( 'view', 'edit', 'embed' ),
1727 'password' => array(
1728 'description' => __( 'A password to protect access to the content and excerpt.' ),
1730 'context' => array( 'edit' ),
1735 $post_type_obj = get_post_type_object( $this->post_type );
1737 if ( $post_type_obj->hierarchical ) {
1738 $schema['properties']['parent'] = array(
1739 'description' => __( 'The ID for the parent of the object.' ),
1740 'type' => 'integer',
1741 'context' => array( 'view', 'edit' ),
1745 $post_type_attributes = array(
1757 $fixed_schemas = array(
1780 'attachment' => array(
1788 foreach ( $post_type_attributes as $attribute ) {
1789 if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
1791 } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
1795 switch ( $attribute ) {
1798 $schema['properties']['title'] = array(
1799 'description' => __( 'The title for the object.' ),
1801 'context' => array( 'view', 'edit', 'embed' ),
1802 'arg_options' => array(
1803 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1805 'properties' => array(
1807 'description' => __( 'Title for the object, as it exists in the database.' ),
1809 'context' => array( 'edit' ),
1811 'rendered' => array(
1812 'description' => __( 'HTML title for the object, transformed for display.' ),
1814 'context' => array( 'view', 'edit', 'embed' ),
1822 $schema['properties']['content'] = array(
1823 'description' => __( 'The content for the object.' ),
1825 'context' => array( 'view', 'edit' ),
1826 'arg_options' => array(
1827 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1829 'properties' => array(
1831 'description' => __( 'Content for the object, as it exists in the database.' ),
1833 'context' => array( 'edit' ),
1835 'rendered' => array(
1836 'description' => __( 'HTML content for the object, transformed for display.' ),
1838 'context' => array( 'view', 'edit' ),
1841 'protected' => array(
1842 'description' => __( 'Whether the content is protected with a password.' ),
1843 'type' => 'boolean',
1844 'context' => array( 'view', 'edit', 'embed' ),
1852 $schema['properties']['author'] = array(
1853 'description' => __( 'The ID for the author of the object.' ),
1854 'type' => 'integer',
1855 'context' => array( 'view', 'edit', 'embed' ),
1860 $schema['properties']['excerpt'] = array(
1861 'description' => __( 'The excerpt for the object.' ),
1863 'context' => array( 'view', 'edit', 'embed' ),
1864 'arg_options' => array(
1865 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1867 'properties' => array(
1869 'description' => __( 'Excerpt for the object, as it exists in the database.' ),
1871 'context' => array( 'edit' ),
1873 'rendered' => array(
1874 'description' => __( 'HTML excerpt for the object, transformed for display.' ),
1876 'context' => array( 'view', 'edit', 'embed' ),
1879 'protected' => array(
1880 'description' => __( 'Whether the excerpt is protected with a password.' ),
1881 'type' => 'boolean',
1882 'context' => array( 'view', 'edit', 'embed' ),
1890 $schema['properties']['featured_media'] = array(
1891 'description' => __( 'The ID of the featured media for the object.' ),
1892 'type' => 'integer',
1893 'context' => array( 'view', 'edit' ),
1898 $schema['properties']['comment_status'] = array(
1899 'description' => __( 'Whether or not comments are open on the object.' ),
1901 'enum' => array( 'open', 'closed' ),
1902 'context' => array( 'view', 'edit' ),
1904 $schema['properties']['ping_status'] = array(
1905 'description' => __( 'Whether or not the object can be pinged.' ),
1907 'enum' => array( 'open', 'closed' ),
1908 'context' => array( 'view', 'edit' ),
1912 case 'page-attributes':
1913 $schema['properties']['menu_order'] = array(
1914 'description' => __( 'The order of the object in relation to other object of its type.' ),
1915 'type' => 'integer',
1916 'context' => array( 'view', 'edit' ),
1920 case 'post-formats':
1921 $supports_formats = get_theme_support( 'post-formats' );
1922 $schema['properties']['format'] = array(
1923 'description' => __( 'The format for the object.' ),
1925 'enum' => array_merge( array( 'standard' ), $supports_formats ? array_values( $supports_formats[0] ) : array() ),
1926 'context' => array( 'view', 'edit' ),
1930 case 'custom-fields':
1931 $schema['properties']['meta'] = $this->meta->get_field_schema();
1937 if ( 'post' === $this->post_type ) {
1938 $schema['properties']['sticky'] = array(
1939 'description' => __( 'Whether or not the object should be treated as sticky.' ),
1940 'type' => 'boolean',
1941 'context' => array( 'view', 'edit' ),
1945 $schema['properties']['template'] = array(
1946 'description' => __( 'The theme file to use to display the object.' ),
1948 'enum' => array_merge( array_keys( wp_get_theme()->get_page_templates( null, $this->post_type ) ), array( '' ) ),
1949 'context' => array( 'view', 'edit' ),
1952 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1953 foreach ( $taxonomies as $taxonomy ) {
1954 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1955 $schema['properties'][ $base ] = array(
1956 /* translators: %s: taxonomy name */
1957 'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
1960 'type' => 'integer',
1962 'context' => array( 'view', 'edit' ),
1966 return $this->add_additional_fields_schema( $schema );
1970 * Retrieves the query params for the posts collection.
1975 * @return array Collection parameters.
1977 public function get_collection_params() {
1978 $params = parent::get_collection_params();
1980 $params['context']['default'] = 'view';
1982 $params['after'] = array(
1983 'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
1985 'format' => 'date-time',
1988 if ( post_type_supports( $this->post_type, 'author' ) ) {
1989 $params['author'] = array(
1990 'description' => __( 'Limit result set to posts assigned to specific authors.' ),
1993 'type' => 'integer',
1995 'default' => array(),
1997 $params['author_exclude'] = array(
1998 'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
2001 'type' => 'integer',
2003 'default' => array(),
2007 $params['before'] = array(
2008 'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
2010 'format' => 'date-time',
2013 $params['exclude'] = array(
2014 'description' => __( 'Ensure result set excludes specific IDs.' ),
2017 'type' => 'integer',
2019 'default' => array(),
2022 $params['include'] = array(
2023 'description' => __( 'Limit result set to specific IDs.' ),
2026 'type' => 'integer',
2028 'default' => array(),
2031 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2032 $params['menu_order'] = array(
2033 'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
2034 'type' => 'integer',
2038 $params['offset'] = array(
2039 'description' => __( 'Offset the result set by a specific number of items.' ),
2040 'type' => 'integer',
2043 $params['order'] = array(
2044 'description' => __( 'Order sort attribute ascending or descending.' ),
2046 'default' => 'desc',
2047 'enum' => array( 'asc', 'desc' ),
2050 $params['orderby'] = array(
2051 'description' => __( 'Sort collection by object attribute.' ),
2053 'default' => 'date',
2064 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2065 $params['orderby']['enum'][] = 'menu_order';
2068 $post_type_obj = get_post_type_object( $this->post_type );
2070 if ( $post_type_obj->hierarchical || 'attachment' === $this->post_type ) {
2071 $params['parent'] = array(
2072 'description' => __( 'Limit result set to those of particular parent IDs.' ),
2075 'type' => 'integer',
2077 'default' => array(),
2079 $params['parent_exclude'] = array(
2080 'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
2083 'type' => 'integer',
2085 'default' => array(),
2089 $params['slug'] = array(
2090 'description' => __( 'Limit result set to posts with one or more specific slugs.' ),
2095 'sanitize_callback' => 'wp_parse_slug_list',
2098 $params['status'] = array(
2099 'default' => 'publish',
2100 'description' => __( 'Limit result set to posts assigned one or more statuses.' ),
2103 'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
2106 'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
2109 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2111 foreach ( $taxonomies as $taxonomy ) {
2112 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
2114 $params[ $base ] = array(
2115 /* translators: %s: taxonomy name */
2116 'description' => sprintf( __( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.' ), $base ),
2119 'type' => 'integer',
2121 'default' => array(),
2124 $params[ $base . '_exclude' ] = array(
2125 /* translators: %s: taxonomy name */
2126 'description' => sprintf( __( 'Limit result set to all items except those that have the specified term assigned in the %s taxonomy.' ), $base ),
2129 'type' => 'integer',
2131 'default' => array(),
2135 if ( 'post' === $this->post_type ) {
2136 $params['sticky'] = array(
2137 'description' => __( 'Limit result set to items that are sticky.' ),
2138 'type' => 'boolean',
2143 * Filter collection parameters for the posts controller.
2145 * The dynamic part of the filter `$this->post_type` refers to the post
2146 * type slug for the controller.
2148 * This filter registers the collection parameter, but does not map the
2149 * collection parameter to an internal WP_Query parameter. Use the
2150 * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
2154 * @param $params JSON Schema-formatted collection parameters.
2155 * @param WP_Post_Type $post_type_obj Post type object.
2157 return apply_filters( "rest_{$this->post_type}_collection_params", $params, $post_type_obj );
2161 * Sanitizes and validates the list of post statuses, including whether the
2162 * user can query private statuses.
2167 * @param string|array $statuses One or more post statuses.
2168 * @param WP_REST_Request $request Full details about the request.
2169 * @param string $parameter Additional parameter to pass to validation.
2170 * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
2172 public function sanitize_post_statuses( $statuses, $request, $parameter ) {
2173 $statuses = wp_parse_slug_list( $statuses );
2175 // The default status is different in WP_REST_Attachments_Controller
2176 $attributes = $request->get_attributes();
2177 $default_status = $attributes['args']['status']['default'];
2179 foreach ( $statuses as $status ) {
2180 if ( $status === $default_status ) {
2184 $post_type_obj = get_post_type_object( $this->post_type );
2186 if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
2187 $result = rest_validate_request_arg( $status, $request, $parameter );
2188 if ( is_wp_error( $result ) ) {
2192 return new WP_Error( 'rest_forbidden_status', __( 'Status is forbidden.' ), array( 'status' => rest_authorization_required_code() ) );