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 $schema = $this->get_item_schema();
81 $get_item_args = array(
82 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
84 if ( isset( $schema['properties']['password'] ) ) {
85 $get_item_args['password'] = array(
86 'description' => __( 'The password for the post if it is password protected.' ),
90 register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
92 'methods' => WP_REST_Server::READABLE,
93 'callback' => array( $this, 'get_item' ),
94 'permission_callback' => array( $this, 'get_item_permissions_check' ),
95 'args' => $get_item_args,
98 'methods' => WP_REST_Server::EDITABLE,
99 'callback' => array( $this, 'update_item' ),
100 'permission_callback' => array( $this, 'update_item_permissions_check' ),
101 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
104 'methods' => WP_REST_Server::DELETABLE,
105 'callback' => array( $this, 'delete_item' ),
106 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
111 'description' => __( 'Whether to bypass trash and force deletion.' ),
115 'schema' => array( $this, 'get_public_item_schema' ),
120 * Checks if a given request has access to read posts.
125 * @param WP_REST_Request $request Full details about the request.
126 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
128 public function get_items_permissions_check( $request ) {
130 $post_type = get_post_type_object( $this->post_type );
132 if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
133 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() ) );
140 * Retrieves a collection of posts.
145 * @param WP_REST_Request $request Full details about the request.
146 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
148 public function get_items( $request ) {
150 // Ensure a search string is set in case the orderby is set to 'relevance'.
151 if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
152 return new WP_Error( 'rest_no_search_term_defined', __( 'You need to define a search term to order by relevance.' ), array( 'status' => 400 ) );
155 // Ensure an include parameter is set in case the orderby is set to 'include'.
156 if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
157 return new WP_Error( 'rest_orderby_include_missing_include', sprintf( __( 'Missing parameter(s): %s' ), 'include' ), array( 'status' => 400 ) );
160 // Retrieve the list of registered collection query parameters.
161 $registered = $this->get_collection_params();
165 * This array defines mappings between public API query parameters whose
166 * values are accepted as-passed, and their internal WP_Query parameter
167 * name equivalents (some are the same). Only values which are also
168 * present in $registered will be set.
170 $parameter_mappings = array(
171 'author' => 'author__in',
172 'author_exclude' => 'author__not_in',
173 'exclude' => 'post__not_in',
174 'include' => 'post__in',
175 'menu_order' => 'menu_order',
176 'offset' => 'offset',
178 'orderby' => 'orderby',
180 'parent' => 'post_parent__in',
181 'parent_exclude' => 'post_parent__not_in',
183 'slug' => 'post_name__in',
184 'status' => 'post_status',
188 * For each known parameter which is both registered and present in the request,
189 * set the parameter's value on the query $args.
191 foreach ( $parameter_mappings as $api_param => $wp_param ) {
192 if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
193 $args[ $wp_param ] = $request[ $api_param ];
197 // Check for & assign any parameters which require special handling or setting.
198 $args['date_query'] = array();
200 // Set before into date query. Date query must be specified as an array of an array.
201 if ( isset( $registered['before'], $request['before'] ) ) {
202 $args['date_query'][0]['before'] = $request['before'];
205 // Set after into date query. Date query must be specified as an array of an array.
206 if ( isset( $registered['after'], $request['after'] ) ) {
207 $args['date_query'][0]['after'] = $request['after'];
210 // Ensure our per_page parameter overrides any provided posts_per_page filter.
211 if ( isset( $registered['per_page'] ) ) {
212 $args['posts_per_page'] = $request['per_page'];
215 if ( isset( $registered['sticky'], $request['sticky'] ) ) {
216 $sticky_posts = get_option( 'sticky_posts', array() );
217 if ( $sticky_posts && $request['sticky'] ) {
219 * As post__in will be used to only get sticky posts,
220 * we have to support the case where post__in was already
223 $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
226 * If we intersected, but there are no post ids in common,
227 * WP_Query won't return "no posts" for post__in = array()
228 * so we have to fake it a bit.
230 if ( ! $args['post__in'] ) {
231 $args['post__in'] = array( -1 );
233 } elseif ( $sticky_posts ) {
235 * As post___not_in will be used to only get posts that
236 * are not sticky, we have to support the case where post__not_in
237 * was already specified.
239 $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
243 // Force the post_type argument, since it's not a user input variable.
244 $args['post_type'] = $this->post_type;
247 * Filters the query arguments for a request.
249 * Enables adding extra arguments or setting defaults for a post collection request.
253 * @link https://developer.wordpress.org/reference/classes/wp_query/
255 * @param array $args Key value array of query var to query value.
256 * @param WP_REST_Request $request The request used.
258 $args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
259 $query_args = $this->prepare_items_query( $args, $request );
261 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
263 foreach ( $taxonomies as $taxonomy ) {
264 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
265 $tax_exclude = $base . '_exclude';
267 if ( ! empty( $request[ $base ] ) ) {
268 $query_args['tax_query'][] = array(
269 'taxonomy' => $taxonomy->name,
270 'field' => 'term_id',
271 'terms' => $request[ $base ],
272 'include_children' => false,
276 if ( ! empty( $request[ $tax_exclude ] ) ) {
277 $query_args['tax_query'][] = array(
278 'taxonomy' => $taxonomy->name,
279 'field' => 'term_id',
280 'terms' => $request[ $tax_exclude ],
281 'include_children' => false,
282 'operator' => 'NOT IN',
287 $posts_query = new WP_Query();
288 $query_result = $posts_query->query( $query_args );
290 // Allow access to all password protected posts if the context is edit.
291 if ( 'edit' === $request['context'] ) {
292 add_filter( 'post_password_required', '__return_false' );
297 foreach ( $query_result as $post ) {
298 if ( ! $this->check_read_permission( $post ) ) {
302 $data = $this->prepare_item_for_response( $post, $request );
303 $posts[] = $this->prepare_response_for_collection( $data );
307 if ( 'edit' === $request['context'] ) {
308 remove_filter( 'post_password_required', '__return_false' );
311 $page = (int) $query_args['paged'];
312 $total_posts = $posts_query->found_posts;
314 if ( $total_posts < 1 ) {
315 // Out-of-bounds, run the query again without LIMIT for total count.
316 unset( $query_args['paged'] );
318 $count_query = new WP_Query();
319 $count_query->query( $query_args );
320 $total_posts = $count_query->found_posts;
323 $max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
324 $response = rest_ensure_response( $posts );
326 $response->header( 'X-WP-Total', (int) $total_posts );
327 $response->header( 'X-WP-TotalPages', (int) $max_pages );
329 $request_params = $request->get_query_params();
330 $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
333 $prev_page = $page - 1;
335 if ( $prev_page > $max_pages ) {
336 $prev_page = $max_pages;
339 $prev_link = add_query_arg( 'page', $prev_page, $base );
340 $response->link_header( 'prev', $prev_link );
342 if ( $max_pages > $page ) {
343 $next_page = $page + 1;
344 $next_link = add_query_arg( 'page', $next_page, $base );
346 $response->link_header( 'next', $next_link );
353 * Checks if a given request has access to read a post.
358 * @param WP_REST_Request $request Full details about the request.
359 * @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise.
361 public function get_item_permissions_check( $request ) {
363 $post = get_post( (int) $request['id'] );
365 if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
366 return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
369 if ( $post && ! empty( $request['password'] ) ) {
370 // Check post password, and return error if invalid.
371 if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
372 return new WP_Error( 'rest_post_incorrect_password', __( 'Incorrect post password.' ), array( 'status' => 403 ) );
376 // Allow access to all password protected posts if the context is edit.
377 if ( 'edit' === $request['context'] ) {
378 add_filter( 'post_password_required', '__return_false' );
382 return $this->check_read_permission( $post );
389 * Checks if the user can access password-protected content.
391 * This method determines whether we need to override the regular password
392 * check in core with a filter.
397 * @param WP_Post $post Post to check against.
398 * @param WP_REST_Request $request Request data to check.
399 * @return bool True if the user can access password-protected content, otherwise false.
401 public function can_access_password_content( $post, $request ) {
402 if ( empty( $post->post_password ) ) {
403 // No filter required.
407 // Edit context always gets access to password-protected posts.
408 if ( 'edit' === $request['context'] ) {
412 // No password, no auth.
413 if ( empty( $request['password'] ) ) {
417 // Double-check the request password.
418 return hash_equals( $post->post_password, $request['password'] );
422 * Retrieves a single post.
427 * @param WP_REST_Request $request Full details about the request.
428 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
430 public function get_item( $request ) {
431 $id = (int) $request['id'];
432 $post = get_post( $id );
434 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
435 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
438 $data = $this->prepare_item_for_response( $post, $request );
439 $response = rest_ensure_response( $data );
441 if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) {
442 $response->link_header( 'alternate', get_permalink( $id ), array( 'type' => 'text/html' ) );
449 * Checks if a given request has access to create a post.
454 * @param WP_REST_Request $request Full details about the request.
455 * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
457 public function create_item_permissions_check( $request ) {
459 $post_type = get_post_type_object( $this->post_type );
461 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
462 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() ) );
465 if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
466 return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
469 if ( ! current_user_can( $post_type->cap->create_posts ) ) {
470 return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
473 if ( ! $this->check_assign_terms_permission( $request ) ) {
474 return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
481 * Creates a single post.
486 * @param WP_REST_Request $request Full details about the request.
487 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
489 public function create_item( $request ) {
490 if ( ! empty( $request['id'] ) ) {
491 return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
494 $prepared_post = $this->prepare_item_for_database( $request );
496 if ( is_wp_error( $prepared_post ) ) {
497 return $prepared_post;
500 $prepared_post->post_type = $this->post_type;
502 $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true );
504 if ( is_wp_error( $post_id ) ) {
506 if ( 'db_insert_error' === $post_id->get_error_code() ) {
507 $post_id->add_data( array( 'status' => 500 ) );
509 $post_id->add_data( array( 'status' => 400 ) );
515 $post = get_post( $post_id );
518 * Fires after a single post is created or updated via the REST API.
520 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
524 * @param WP_Post $post Inserted or updated post object.
525 * @param WP_REST_Request $request Request object.
526 * @param bool $creating True when creating a post, false when updating.
528 do_action( "rest_insert_{$this->post_type}", $post, $request, true );
530 $schema = $this->get_item_schema();
532 if ( ! empty( $schema['properties']['sticky'] ) ) {
533 if ( ! empty( $request['sticky'] ) ) {
534 stick_post( $post_id );
536 unstick_post( $post_id );
540 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
541 $this->handle_featured_media( $request['featured_media'], $post_id );
544 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
545 set_post_format( $post, $request['format'] );
548 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
549 $this->handle_template( $request['template'], $post_id );
552 $terms_update = $this->handle_terms( $post_id, $request );
554 if ( is_wp_error( $terms_update ) ) {
555 return $terms_update;
558 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
559 $meta_update = $this->meta->update_value( $request['meta'], $post_id );
561 if ( is_wp_error( $meta_update ) ) {
566 $post = get_post( $post_id );
567 $fields_update = $this->update_additional_fields_for_object( $post, $request );
569 if ( is_wp_error( $fields_update ) ) {
570 return $fields_update;
573 $request->set_param( 'context', 'edit' );
575 $response = $this->prepare_item_for_response( $post, $request );
576 $response = rest_ensure_response( $response );
578 $response->set_status( 201 );
579 $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $post_id ) ) );
585 * Checks if a given request has access to update a post.
590 * @param WP_REST_Request $request Full details about the request.
591 * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
593 public function update_item_permissions_check( $request ) {
595 $post = get_post( $request['id'] );
596 $post_type = get_post_type_object( $this->post_type );
598 if ( $post && ! $this->check_update_permission( $post ) ) {
599 return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
602 if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
603 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() ) );
606 if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
607 return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
610 if ( ! $this->check_assign_terms_permission( $request ) ) {
611 return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
618 * Updates a single post.
623 * @param WP_REST_Request $request Full details about the request.
624 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
626 public function update_item( $request ) {
627 $id = (int) $request['id'];
628 $post = get_post( $id );
630 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
631 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
634 $post = $this->prepare_item_for_database( $request );
636 if ( is_wp_error( $post ) ) {
640 // convert the post object to an array, otherwise wp_update_post will expect non-escaped input.
641 $post_id = wp_update_post( wp_slash( (array) $post ), true );
643 if ( is_wp_error( $post_id ) ) {
644 if ( 'db_update_error' === $post_id->get_error_code() ) {
645 $post_id->add_data( array( 'status' => 500 ) );
647 $post_id->add_data( array( 'status' => 400 ) );
652 $post = get_post( $post_id );
654 /* This action is documented in lib/endpoints/class-wp-rest-controller.php */
655 do_action( "rest_insert_{$this->post_type}", $post, $request, false );
657 $schema = $this->get_item_schema();
659 if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
660 set_post_format( $post, $request['format'] );
663 if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
664 $this->handle_featured_media( $request['featured_media'], $post_id );
667 if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) {
668 if ( ! empty( $request['sticky'] ) ) {
669 stick_post( $post_id );
671 unstick_post( $post_id );
675 if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
676 $this->handle_template( $request['template'], $post->ID );
679 $terms_update = $this->handle_terms( $post->ID, $request );
681 if ( is_wp_error( $terms_update ) ) {
682 return $terms_update;
685 if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
686 $meta_update = $this->meta->update_value( $request['meta'], $post->ID );
688 if ( is_wp_error( $meta_update ) ) {
693 $post = get_post( $post_id );
694 $fields_update = $this->update_additional_fields_for_object( $post, $request );
696 if ( is_wp_error( $fields_update ) ) {
697 return $fields_update;
700 $request->set_param( 'context', 'edit' );
702 $response = $this->prepare_item_for_response( $post, $request );
704 return rest_ensure_response( $response );
708 * Checks if a given request has access to delete a post.
713 * @param WP_REST_Request $request Full details about the request.
714 * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
716 public function delete_item_permissions_check( $request ) {
718 $post = get_post( $request['id'] );
720 if ( $post && ! $this->check_delete_permission( $post ) ) {
721 return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
728 * Deletes a single post.
733 * @param WP_REST_Request $request Full details about the request.
734 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
736 public function delete_item( $request ) {
737 $id = (int) $request['id'];
738 $force = (bool) $request['force'];
740 $post = get_post( $id );
742 if ( empty( $id ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
743 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
746 $supports_trash = ( EMPTY_TRASH_DAYS > 0 );
748 if ( 'attachment' === $post->post_type ) {
749 $supports_trash = $supports_trash && MEDIA_TRASH;
753 * Filters whether a post is trashable.
755 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
757 * Pass false to disable trash support for the post.
761 * @param bool $supports_trash Whether the post type support trashing.
762 * @param WP_Post $post The Post object being considered for trashing support.
764 $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );
766 if ( ! $this->check_delete_permission( $post ) ) {
767 return new WP_Error( 'rest_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
770 $request->set_param( 'context', 'edit' );
773 // If we're forcing, then delete permanently.
775 $previous = $this->prepare_item_for_response( $post, $request );
776 $result = wp_delete_post( $id, true );
777 $response = new WP_REST_Response();
778 $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
780 // If we don't support trashing for this type, error out.
781 if ( ! $supports_trash ) {
782 return new WP_Error( 'rest_trash_not_supported', __( 'The post does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
785 // Otherwise, only trash if we haven't already.
786 if ( 'trash' === $post->post_status ) {
787 return new WP_Error( 'rest_already_trashed', __( 'The post has already been deleted.' ), array( 'status' => 410 ) );
790 // (Note that internally this falls through to `wp_delete_post` if
791 // the trash is disabled.)
792 $result = wp_trash_post( $id );
793 $post = get_post( $id );
794 $response = $this->prepare_item_for_response( $post, $request );
798 return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
802 * Fires immediately after a single post is deleted or trashed via the REST API.
804 * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
808 * @param object $post The deleted or trashed post.
809 * @param WP_REST_Response $response The response data.
810 * @param WP_REST_Request $request The request sent to the API.
812 do_action( "rest_delete_{$this->post_type}", $post, $response, $request );
818 * Determines the allowed query_vars for a get_items() response and prepares
824 * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
825 * @param WP_REST_Request $request Optional. Full details about the request.
826 * @return array Items query arguments.
828 protected function prepare_items_query( $prepared_args = array(), $request = null ) {
829 $query_args = array();
831 foreach ( $prepared_args as $key => $value ) {
833 * Filters the query_vars used in get_items() for the constructed query.
835 * The dynamic portion of the hook name, `$key`, refers to the query_var key.
839 * @param string $value The query_var value.
841 $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value );
844 if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
845 $query_args['ignore_sticky_posts'] = true;
848 // Map to proper WP_Query orderby param.
849 if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
850 $orderby_mappings = array(
852 'include' => 'post__in',
853 'slug' => 'post_name',
856 if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
857 $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
865 * Checks the post_date_gmt or modified_gmt and prepare any post or
866 * modified date for single post output.
871 * @param string $date_gmt GMT publication time.
872 * @param string|null $date Optional. Local publication time. Default null.
873 * @return string|null ISO8601/RFC3339 formatted datetime.
875 protected function prepare_date_response( $date_gmt, $date = null ) {
876 // Use the date if passed.
877 if ( isset( $date ) ) {
878 return mysql_to_rfc3339( $date );
881 // Return null if $date_gmt is empty/zeros.
882 if ( '0000-00-00 00:00:00' === $date_gmt ) {
886 // Return the formatted datetime.
887 return mysql_to_rfc3339( $date_gmt );
891 * Prepares a single post for create or update.
896 * @param WP_REST_Request $request Request object.
897 * @return stdClass|WP_Error Post object or WP_Error.
899 protected function prepare_item_for_database( $request ) {
900 $prepared_post = new stdClass;
903 if ( isset( $request['id'] ) ) {
904 $prepared_post->ID = absint( $request['id'] );
907 $schema = $this->get_item_schema();
910 if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
911 if ( is_string( $request['title'] ) ) {
912 $prepared_post->post_title = $request['title'];
913 } elseif ( ! empty( $request['title']['raw'] ) ) {
914 $prepared_post->post_title = $request['title']['raw'];
919 if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) {
920 if ( is_string( $request['content'] ) ) {
921 $prepared_post->post_content = $request['content'];
922 } elseif ( isset( $request['content']['raw'] ) ) {
923 $prepared_post->post_content = $request['content']['raw'];
928 if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) {
929 if ( is_string( $request['excerpt'] ) ) {
930 $prepared_post->post_excerpt = $request['excerpt'];
931 } elseif ( isset( $request['excerpt']['raw'] ) ) {
932 $prepared_post->post_excerpt = $request['excerpt']['raw'];
937 if ( empty( $request['id'] ) ) {
938 // Creating new post, use default type for the controller.
939 $prepared_post->post_type = $this->post_type;
941 // Updating a post, use previous type.
942 $prepared_post->post_type = get_post_type( $request['id'] );
945 $post_type = get_post_type_object( $prepared_post->post_type );
948 if ( ! empty( $schema['properties']['status'] ) && isset( $request['status'] ) ) {
949 $status = $this->handle_status_param( $request['status'], $post_type );
951 if ( is_wp_error( $status ) ) {
955 $prepared_post->post_status = $status;
959 if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) {
960 $date_data = rest_get_date_with_gmt( $request['date'] );
962 if ( ! empty( $date_data ) ) {
963 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
965 } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) {
966 $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
968 if ( ! empty( $date_data ) ) {
969 list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
974 if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) {
975 $prepared_post->post_name = $request['slug'];
979 if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) {
980 $post_author = (int) $request['author'];
982 if ( get_current_user_id() !== $post_author ) {
983 $user_obj = get_userdata( $post_author );
986 return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) );
990 $prepared_post->post_author = $post_author;
994 if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) {
995 $prepared_post->post_password = $request['password'];
997 if ( '' !== $request['password'] ) {
998 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
999 return new WP_Error( 'rest_invalid_field', __( 'A post can not be sticky and have a password.' ), array( 'status' => 400 ) );
1002 if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) {
1003 return new WP_Error( 'rest_invalid_field', __( 'A sticky post can not be password protected.' ), array( 'status' => 400 ) );
1008 if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
1009 if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) {
1010 return new WP_Error( 'rest_invalid_field', __( 'A password protected post can not be set to sticky.' ), array( 'status' => 400 ) );
1015 if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) {
1016 if ( 0 === (int) $request['parent'] ) {
1017 $prepared_post->post_parent = 0;
1019 $parent = get_post( (int) $request['parent'] );
1020 if ( empty( $parent ) ) {
1021 return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) );
1023 $prepared_post->post_parent = (int) $parent->ID;
1028 if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) {
1029 $prepared_post->menu_order = (int) $request['menu_order'];
1033 if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) {
1034 $prepared_post->comment_status = $request['comment_status'];
1038 if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) {
1039 $prepared_post->ping_status = $request['ping_status'];
1043 * Filters a post before it is inserted via the REST API.
1045 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1049 * @param stdClass $prepared_post An object representing a single post prepared
1050 * for inserting or updating the database.
1051 * @param WP_REST_Request $request Request object.
1053 return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );
1058 * Determines validity and normalizes the given status parameter.
1063 * @param string $post_status Post status.
1064 * @param object $post_type Post type.
1065 * @return string|WP_Error Post status or WP_Error if lacking the proper permission.
1067 protected function handle_status_param( $post_status, $post_type ) {
1069 switch ( $post_status ) {
1074 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1075 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() ) );
1080 if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
1081 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() ) );
1085 if ( ! get_post_status_object( $post_status ) ) {
1086 $post_status = 'draft';
1091 return $post_status;
1095 * Determines the featured media based on a request param.
1100 * @param int $featured_media Featured Media ID.
1101 * @param int $post_id Post ID.
1102 * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
1104 protected function handle_featured_media( $featured_media, $post_id ) {
1106 $featured_media = (int) $featured_media;
1107 if ( $featured_media ) {
1108 $result = set_post_thumbnail( $post_id, $featured_media );
1112 return new WP_Error( 'rest_invalid_featured_media', __( 'Invalid featured media ID.' ), array( 'status' => 400 ) );
1115 return delete_post_thumbnail( $post_id );
1121 * Sets the template for a post.
1126 * @param string $template Page template filename.
1127 * @param integer $post_id Post ID.
1129 public function handle_template( $template, $post_id ) {
1130 if ( in_array( $template, array_keys( wp_get_theme()->get_page_templates( get_post( $post_id ) ) ), true ) ) {
1131 update_post_meta( $post_id, '_wp_page_template', $template );
1133 update_post_meta( $post_id, '_wp_page_template', '' );
1138 * Updates the post's terms from a REST request.
1143 * @param int $post_id The post ID to update the terms form.
1144 * @param WP_REST_Request $request The request object with post and terms data.
1145 * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null.
1147 protected function handle_terms( $post_id, $request ) {
1148 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1150 foreach ( $taxonomies as $taxonomy ) {
1151 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1153 if ( ! isset( $request[ $base ] ) ) {
1157 $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name );
1159 if ( is_wp_error( $result ) ) {
1166 * Checks whether current user can assign all terms sent with the current request.
1170 * @param WP_REST_Request $request The request object with post and terms data.
1171 * @return bool Whether the current user can assign the provided terms.
1173 protected function check_assign_terms_permission( $request ) {
1174 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1175 foreach ( $taxonomies as $taxonomy ) {
1176 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1178 if ( ! isset( $request[ $base ] ) ) {
1182 foreach ( $request[ $base ] as $term_id ) {
1183 // Invalid terms will be rejected later.
1184 if ( ! get_term( $term_id, $taxonomy->name ) ) {
1188 if ( ! current_user_can( 'assign_term', (int) $term_id ) ) {
1198 * Checks if a given post type can be viewed or managed.
1203 * @param object|string $post_type Post type name or object.
1204 * @return bool Whether the post type is allowed in REST.
1206 protected function check_is_post_type_allowed( $post_type ) {
1207 if ( ! is_object( $post_type ) ) {
1208 $post_type = get_post_type_object( $post_type );
1211 if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) {
1219 * Checks if a post can be read.
1221 * Correctly handles posts with the inherit status.
1226 * @param object $post Post object.
1227 * @return bool Whether the post can be read.
1229 public function check_read_permission( $post ) {
1230 $post_type = get_post_type_object( $post->post_type );
1231 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1235 // Is the post readable?
1236 if ( 'publish' === $post->post_status || current_user_can( $post_type->cap->read_post, $post->ID ) ) {
1240 $post_status_obj = get_post_status_object( $post->post_status );
1241 if ( $post_status_obj && $post_status_obj->public ) {
1245 // Can we read the parent if we're inheriting?
1246 if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
1247 $parent = get_post( $post->post_parent );
1248 return $this->check_read_permission( $parent );
1252 * If there isn't a parent, but the status is set to inherit, assume
1253 * it's published (as per get_post_status()).
1255 if ( 'inherit' === $post->post_status ) {
1263 * Checks if a post can be edited.
1268 * @param object $post Post object.
1269 * @return bool Whether the post can be edited.
1271 protected function check_update_permission( $post ) {
1272 $post_type = get_post_type_object( $post->post_type );
1274 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1278 return current_user_can( $post_type->cap->edit_post, $post->ID );
1282 * Checks if a post can be created.
1287 * @param object $post Post object.
1288 * @return bool Whether the post can be created.
1290 protected function check_create_permission( $post ) {
1291 $post_type = get_post_type_object( $post->post_type );
1293 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1297 return current_user_can( $post_type->cap->create_posts );
1301 * Checks if a post can be deleted.
1306 * @param object $post Post object.
1307 * @return bool Whether the post can be deleted.
1309 protected function check_delete_permission( $post ) {
1310 $post_type = get_post_type_object( $post->post_type );
1312 if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
1316 return current_user_can( $post_type->cap->delete_post, $post->ID );
1320 * Prepares a single post output for response.
1325 * @param WP_Post $post Post object.
1326 * @param WP_REST_Request $request Request object.
1327 * @return WP_REST_Response Response object.
1329 public function prepare_item_for_response( $post, $request ) {
1330 $GLOBALS['post'] = $post;
1332 setup_postdata( $post );
1334 $schema = $this->get_item_schema();
1336 // Base fields for every post.
1339 if ( ! empty( $schema['properties']['id'] ) ) {
1340 $data['id'] = $post->ID;
1343 if ( ! empty( $schema['properties']['date'] ) ) {
1344 $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
1347 if ( ! empty( $schema['properties']['date_gmt'] ) ) {
1348 $data['date_gmt'] = $this->prepare_date_response( $post->post_date_gmt );
1351 if ( ! empty( $schema['properties']['guid'] ) ) {
1352 $data['guid'] = array(
1353 /** This filter is documented in wp-includes/post-template.php */
1354 'rendered' => apply_filters( 'get_the_guid', $post->guid ),
1355 'raw' => $post->guid,
1359 if ( ! empty( $schema['properties']['modified'] ) ) {
1360 $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
1363 if ( ! empty( $schema['properties']['modified_gmt'] ) ) {
1364 $data['modified_gmt'] = $this->prepare_date_response( $post->post_modified_gmt );
1367 if ( ! empty( $schema['properties']['password'] ) ) {
1368 $data['password'] = $post->post_password;
1371 if ( ! empty( $schema['properties']['slug'] ) ) {
1372 $data['slug'] = $post->post_name;
1375 if ( ! empty( $schema['properties']['status'] ) ) {
1376 $data['status'] = $post->post_status;
1379 if ( ! empty( $schema['properties']['type'] ) ) {
1380 $data['type'] = $post->post_type;
1383 if ( ! empty( $schema['properties']['link'] ) ) {
1384 $data['link'] = get_permalink( $post->ID );
1387 if ( ! empty( $schema['properties']['title'] ) ) {
1388 add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1390 $data['title'] = array(
1391 'raw' => $post->post_title,
1392 'rendered' => get_the_title( $post->ID ),
1395 remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
1398 $has_password_filter = false;
1400 if ( $this->can_access_password_content( $post, $request ) ) {
1401 // Allow access to the post, permissions already checked before.
1402 add_filter( 'post_password_required', '__return_false' );
1404 $has_password_filter = true;
1407 if ( ! empty( $schema['properties']['content'] ) ) {
1408 $data['content'] = array(
1409 'raw' => $post->post_content,
1410 /** This filter is documented in wp-includes/post-template.php */
1411 'rendered' => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
1412 'protected' => (bool) $post->post_password,
1416 if ( ! empty( $schema['properties']['excerpt'] ) ) {
1417 /** This filter is documented in wp-includes/post-template.php */
1418 $excerpt = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
1419 $data['excerpt'] = array(
1420 'raw' => $post->post_excerpt,
1421 'rendered' => post_password_required( $post ) ? '' : $excerpt,
1422 'protected' => (bool) $post->post_password,
1426 if ( $has_password_filter ) {
1428 remove_filter( 'post_password_required', '__return_false' );
1431 if ( ! empty( $schema['properties']['author'] ) ) {
1432 $data['author'] = (int) $post->post_author;
1435 if ( ! empty( $schema['properties']['featured_media'] ) ) {
1436 $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID );
1439 if ( ! empty( $schema['properties']['parent'] ) ) {
1440 $data['parent'] = (int) $post->post_parent;
1443 if ( ! empty( $schema['properties']['menu_order'] ) ) {
1444 $data['menu_order'] = (int) $post->menu_order;
1447 if ( ! empty( $schema['properties']['comment_status'] ) ) {
1448 $data['comment_status'] = $post->comment_status;
1451 if ( ! empty( $schema['properties']['ping_status'] ) ) {
1452 $data['ping_status'] = $post->ping_status;
1455 if ( ! empty( $schema['properties']['sticky'] ) ) {
1456 $data['sticky'] = is_sticky( $post->ID );
1459 if ( ! empty( $schema['properties']['template'] ) ) {
1460 if ( $template = get_page_template_slug( $post->ID ) ) {
1461 $data['template'] = $template;
1463 $data['template'] = '';
1467 if ( ! empty( $schema['properties']['format'] ) ) {
1468 $data['format'] = get_post_format( $post->ID );
1470 // Fill in blank post format.
1471 if ( empty( $data['format'] ) ) {
1472 $data['format'] = 'standard';
1476 if ( ! empty( $schema['properties']['meta'] ) ) {
1477 $data['meta'] = $this->meta->get_value( $post->ID, $request );
1480 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1482 foreach ( $taxonomies as $taxonomy ) {
1483 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1485 if ( ! empty( $schema['properties'][ $base ] ) ) {
1486 $terms = get_the_terms( $post, $taxonomy->name );
1487 $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
1491 $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
1492 $data = $this->add_additional_fields_to_object( $data, $request );
1493 $data = $this->filter_response_by_context( $data, $context );
1495 // Wrap the data in a response object.
1496 $response = rest_ensure_response( $data );
1498 $response->add_links( $this->prepare_links( $post ) );
1501 * Filters the post data for a response.
1503 * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
1507 * @param WP_REST_Response $response The response object.
1508 * @param WP_Post $post Post object.
1509 * @param WP_REST_Request $request Request object.
1511 return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
1515 * Overwrites the default protected title format.
1517 * By default, WordPress will show password protected posts with a title of
1518 * "Protected: %s", as the REST API communicates the protected status of a post
1519 * in a machine readable format, we remove the "Protected: " prefix.
1521 * @return string Protected title format.
1523 public function protected_title_format() {
1528 * Prepares links for the request.
1533 * @param WP_Post $post Post object.
1534 * @return array Links for the given post.
1536 protected function prepare_links( $post ) {
1537 $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
1542 'href' => rest_url( trailingslashit( $base ) . $post->ID ),
1544 'collection' => array(
1545 'href' => rest_url( $base ),
1548 'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
1552 if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
1553 && ! empty( $post->post_author ) ) {
1554 $links['author'] = array(
1555 'href' => rest_url( 'wp/v2/users/' . $post->post_author ),
1556 'embeddable' => true,
1560 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
1561 $replies_url = rest_url( 'wp/v2/comments' );
1562 $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
1564 $links['replies'] = array(
1565 'href' => $replies_url,
1566 'embeddable' => true,
1570 if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
1571 $links['version-history'] = array(
1572 'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions' ),
1576 $post_type_obj = get_post_type_object( $post->post_type );
1578 if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
1579 $links['up'] = array(
1580 'href' => rest_url( trailingslashit( $base ) . (int) $post->post_parent ),
1581 'embeddable' => true,
1585 // If we have a featured media, add that.
1586 if ( $featured_media = get_post_thumbnail_id( $post->ID ) ) {
1587 $image_url = rest_url( 'wp/v2/media/' . $featured_media );
1589 $links['https://api.w.org/featuredmedia'] = array(
1590 'href' => $image_url,
1591 'embeddable' => true,
1595 if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
1596 $attachments_url = rest_url( 'wp/v2/media' );
1597 $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
1599 $links['https://api.w.org/attachment'] = array(
1600 'href' => $attachments_url,
1604 $taxonomies = get_object_taxonomies( $post->post_type );
1606 if ( ! empty( $taxonomies ) ) {
1607 $links['https://api.w.org/term'] = array();
1609 foreach ( $taxonomies as $tax ) {
1610 $taxonomy_obj = get_taxonomy( $tax );
1612 // Skip taxonomies that are not public.
1613 if ( empty( $taxonomy_obj->show_in_rest ) ) {
1617 $tax_base = ! empty( $taxonomy_obj->rest_base ) ? $taxonomy_obj->rest_base : $tax;
1619 $terms_url = add_query_arg(
1622 rest_url( 'wp/v2/' . $tax_base )
1625 $links['https://api.w.org/term'][] = array(
1626 'href' => $terms_url,
1628 'embeddable' => true,
1637 * Retrieves the post's schema, conforming to JSON Schema.
1642 * @return array Item schema data.
1644 public function get_item_schema() {
1647 '$schema' => 'http://json-schema.org/schema#',
1648 'title' => $this->post_type,
1650 // Base properties for every Post.
1651 'properties' => array(
1653 'description' => __( "The date the object was published, in the site's timezone." ),
1655 'format' => 'date-time',
1656 'context' => array( 'view', 'edit', 'embed' ),
1658 'date_gmt' => array(
1659 'description' => __( 'The date the object was published, as GMT.' ),
1661 'format' => 'date-time',
1662 'context' => array( 'view', 'edit' ),
1665 'description' => __( 'The globally unique identifier for the object.' ),
1667 'context' => array( 'view', 'edit' ),
1669 'properties' => array(
1671 'description' => __( 'GUID for the object, as it exists in the database.' ),
1673 'context' => array( 'edit' ),
1676 'rendered' => array(
1677 'description' => __( 'GUID for the object, transformed for display.' ),
1679 'context' => array( 'view', 'edit' ),
1685 'description' => __( 'Unique identifier for the object.' ),
1686 'type' => 'integer',
1687 'context' => array( 'view', 'edit', 'embed' ),
1691 'description' => __( 'URL to the object.' ),
1694 'context' => array( 'view', 'edit', 'embed' ),
1697 'modified' => array(
1698 'description' => __( "The date the object was last modified, in the site's timezone." ),
1700 'format' => 'date-time',
1701 'context' => array( 'view', 'edit' ),
1704 'modified_gmt' => array(
1705 'description' => __( 'The date the object was last modified, as GMT.' ),
1707 'format' => 'date-time',
1708 'context' => array( 'view', 'edit' ),
1712 'description' => __( 'An alphanumeric identifier for the object unique to its type.' ),
1714 'context' => array( 'view', 'edit', 'embed' ),
1715 'arg_options' => array(
1716 'sanitize_callback' => array( $this, 'sanitize_slug' ),
1720 'description' => __( 'A named status for the object.' ),
1722 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ),
1723 'context' => array( 'edit' ),
1726 'description' => __( 'Type of Post for the object.' ),
1728 'context' => array( 'view', 'edit', 'embed' ),
1731 'password' => array(
1732 'description' => __( 'A password to protect access to the content and excerpt.' ),
1734 'context' => array( 'edit' ),
1739 $post_type_obj = get_post_type_object( $this->post_type );
1741 if ( $post_type_obj->hierarchical ) {
1742 $schema['properties']['parent'] = array(
1743 'description' => __( 'The ID for the parent of the object.' ),
1744 'type' => 'integer',
1745 'context' => array( 'view', 'edit' ),
1749 $post_type_attributes = array(
1761 $fixed_schemas = array(
1784 'attachment' => array(
1792 foreach ( $post_type_attributes as $attribute ) {
1793 if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
1795 } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
1799 switch ( $attribute ) {
1802 $schema['properties']['title'] = array(
1803 'description' => __( 'The title for the object.' ),
1805 'context' => array( 'view', 'edit', 'embed' ),
1806 'arg_options' => array(
1807 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1809 'properties' => array(
1811 'description' => __( 'Title for the object, as it exists in the database.' ),
1813 'context' => array( 'edit' ),
1815 'rendered' => array(
1816 'description' => __( 'HTML title for the object, transformed for display.' ),
1818 'context' => array( 'view', 'edit', 'embed' ),
1826 $schema['properties']['content'] = array(
1827 'description' => __( 'The content for the object.' ),
1829 'context' => array( 'view', 'edit' ),
1830 'arg_options' => array(
1831 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1833 'properties' => array(
1835 'description' => __( 'Content for the object, as it exists in the database.' ),
1837 'context' => array( 'edit' ),
1839 'rendered' => array(
1840 'description' => __( 'HTML content for the object, transformed for display.' ),
1842 'context' => array( 'view', 'edit' ),
1845 'protected' => array(
1846 'description' => __( 'Whether the content is protected with a password.' ),
1847 'type' => 'boolean',
1848 'context' => array( 'view', 'edit', 'embed' ),
1856 $schema['properties']['author'] = array(
1857 'description' => __( 'The ID for the author of the object.' ),
1858 'type' => 'integer',
1859 'context' => array( 'view', 'edit', 'embed' ),
1864 $schema['properties']['excerpt'] = array(
1865 'description' => __( 'The excerpt for the object.' ),
1867 'context' => array( 'view', 'edit', 'embed' ),
1868 'arg_options' => array(
1869 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
1871 'properties' => array(
1873 'description' => __( 'Excerpt for the object, as it exists in the database.' ),
1875 'context' => array( 'edit' ),
1877 'rendered' => array(
1878 'description' => __( 'HTML excerpt for the object, transformed for display.' ),
1880 'context' => array( 'view', 'edit', 'embed' ),
1883 'protected' => array(
1884 'description' => __( 'Whether the excerpt is protected with a password.' ),
1885 'type' => 'boolean',
1886 'context' => array( 'view', 'edit', 'embed' ),
1894 $schema['properties']['featured_media'] = array(
1895 'description' => __( 'The ID of the featured media for the object.' ),
1896 'type' => 'integer',
1897 'context' => array( 'view', 'edit' ),
1902 $schema['properties']['comment_status'] = array(
1903 'description' => __( 'Whether or not comments are open on the object.' ),
1905 'enum' => array( 'open', 'closed' ),
1906 'context' => array( 'view', 'edit' ),
1908 $schema['properties']['ping_status'] = array(
1909 'description' => __( 'Whether or not the object can be pinged.' ),
1911 'enum' => array( 'open', 'closed' ),
1912 'context' => array( 'view', 'edit' ),
1916 case 'page-attributes':
1917 $schema['properties']['menu_order'] = array(
1918 'description' => __( 'The order of the object in relation to other object of its type.' ),
1919 'type' => 'integer',
1920 'context' => array( 'view', 'edit' ),
1924 case 'post-formats':
1925 $supports_formats = get_theme_support( 'post-formats' );
1927 // Force to an array. Supports formats can return true even if empty in some cases.
1928 $supports_formats = is_array( $supports_formats ) ? array_values( $supports_formats[0] ) : array();
1930 $supported_formats = array_merge( array( 'standard' ), $supports_formats );
1932 $schema['properties']['format'] = array(
1933 'description' => __( 'The format for the object.' ),
1935 'enum' => $supported_formats,
1936 'context' => array( 'view', 'edit' ),
1940 case 'custom-fields':
1941 $schema['properties']['meta'] = $this->meta->get_field_schema();
1947 if ( 'post' === $this->post_type ) {
1948 $schema['properties']['sticky'] = array(
1949 'description' => __( 'Whether or not the object should be treated as sticky.' ),
1950 'type' => 'boolean',
1951 'context' => array( 'view', 'edit' ),
1955 $schema['properties']['template'] = array(
1956 'description' => __( 'The theme file to use to display the object.' ),
1958 'enum' => array_merge( array_keys( wp_get_theme()->get_page_templates( null, $this->post_type ) ), array( '' ) ),
1959 'context' => array( 'view', 'edit' ),
1962 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
1963 foreach ( $taxonomies as $taxonomy ) {
1964 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
1965 $schema['properties'][ $base ] = array(
1966 /* translators: %s: taxonomy name */
1967 'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
1970 'type' => 'integer',
1972 'context' => array( 'view', 'edit' ),
1976 return $this->add_additional_fields_schema( $schema );
1980 * Retrieves the query params for the posts collection.
1985 * @return array Collection parameters.
1987 public function get_collection_params() {
1988 $query_params = parent::get_collection_params();
1990 $query_params['context']['default'] = 'view';
1992 $query_params['after'] = array(
1993 'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
1995 'format' => 'date-time',
1998 if ( post_type_supports( $this->post_type, 'author' ) ) {
1999 $query_params['author'] = array(
2000 'description' => __( 'Limit result set to posts assigned to specific authors.' ),
2003 'type' => 'integer',
2005 'default' => array(),
2007 $query_params['author_exclude'] = array(
2008 'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
2011 'type' => 'integer',
2013 'default' => array(),
2017 $query_params['before'] = array(
2018 'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
2020 'format' => 'date-time',
2023 $query_params['exclude'] = array(
2024 'description' => __( 'Ensure result set excludes specific IDs.' ),
2027 'type' => 'integer',
2029 'default' => array(),
2032 $query_params['include'] = array(
2033 'description' => __( 'Limit result set to specific IDs.' ),
2036 'type' => 'integer',
2038 'default' => array(),
2041 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2042 $query_params['menu_order'] = array(
2043 'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
2044 'type' => 'integer',
2048 $query_params['offset'] = array(
2049 'description' => __( 'Offset the result set by a specific number of items.' ),
2050 'type' => 'integer',
2053 $query_params['order'] = array(
2054 'description' => __( 'Order sort attribute ascending or descending.' ),
2056 'default' => 'desc',
2057 'enum' => array( 'asc', 'desc' ),
2060 $query_params['orderby'] = array(
2061 'description' => __( 'Sort collection by object attribute.' ),
2063 'default' => 'date',
2074 if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
2075 $query_params['orderby']['enum'][] = 'menu_order';
2078 $post_type = get_post_type_object( $this->post_type );
2080 if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
2081 $query_params['parent'] = array(
2082 'description' => __( 'Limit result set to those of particular parent IDs.' ),
2085 'type' => 'integer',
2087 'default' => array(),
2089 $query_params['parent_exclude'] = array(
2090 'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
2093 'type' => 'integer',
2095 'default' => array(),
2099 $query_params['slug'] = array(
2100 'description' => __( 'Limit result set to posts with one or more specific slugs.' ),
2105 'sanitize_callback' => 'wp_parse_slug_list',
2108 $query_params['status'] = array(
2109 'default' => 'publish',
2110 'description' => __( 'Limit result set to posts assigned one or more statuses.' ),
2113 'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
2116 'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
2119 $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
2121 foreach ( $taxonomies as $taxonomy ) {
2122 $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
2124 $query_params[ $base ] = array(
2125 /* translators: %s: taxonomy name */
2126 'description' => sprintf( __( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.' ), $base ),
2129 'type' => 'integer',
2131 'default' => array(),
2134 $query_params[ $base . '_exclude' ] = array(
2135 /* translators: %s: taxonomy name */
2136 'description' => sprintf( __( 'Limit result set to all items except those that have the specified term assigned in the %s taxonomy.' ), $base ),
2139 'type' => 'integer',
2141 'default' => array(),
2145 if ( 'post' === $this->post_type ) {
2146 $query_params['sticky'] = array(
2147 'description' => __( 'Limit result set to items that are sticky.' ),
2148 'type' => 'boolean',
2153 * Filter collection parameters for the posts controller.
2155 * The dynamic part of the filter `$this->post_type` refers to the post
2156 * type slug for the controller.
2158 * This filter registers the collection parameter, but does not map the
2159 * collection parameter to an internal WP_Query parameter. Use the
2160 * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
2164 * @param array $query_params JSON Schema-formatted collection parameters.
2165 * @param WP_Post_Type $post_type Post type object.
2167 return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
2171 * Sanitizes and validates the list of post statuses, including whether the
2172 * user can query private statuses.
2177 * @param string|array $statuses One or more post statuses.
2178 * @param WP_REST_Request $request Full details about the request.
2179 * @param string $parameter Additional parameter to pass to validation.
2180 * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
2182 public function sanitize_post_statuses( $statuses, $request, $parameter ) {
2183 $statuses = wp_parse_slug_list( $statuses );
2185 // The default status is different in WP_REST_Attachments_Controller
2186 $attributes = $request->get_attributes();
2187 $default_status = $attributes['args']['status']['default'];
2189 foreach ( $statuses as $status ) {
2190 if ( $status === $default_status ) {
2194 $post_type_obj = get_post_type_object( $this->post_type );
2196 if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
2197 $result = rest_validate_request_arg( $status, $request, $parameter );
2198 if ( is_wp_error( $result ) ) {
2202 return new WP_Error( 'rest_forbidden_status', __( 'Status is forbidden.' ), array( 'status' => rest_authorization_required_code() ) );