您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

2266 行
71 KiB

  1. <?php
  2. /**
  3. * REST API: WP_REST_Posts_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core class to access posts via the REST API.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see WP_REST_Controller
  15. */
  16. class WP_REST_Posts_Controller extends WP_REST_Controller {
  17. /**
  18. * Post type.
  19. *
  20. * @since 4.7.0
  21. * @access protected
  22. * @var string
  23. */
  24. protected $post_type;
  25. /**
  26. * Instance of a post meta fields object.
  27. *
  28. * @since 4.7.0
  29. * @access protected
  30. * @var WP_REST_Post_Meta_Fields
  31. */
  32. protected $meta;
  33. /**
  34. * Constructor.
  35. *
  36. * @since 4.7.0
  37. * @access public
  38. *
  39. * @param string $post_type Post type.
  40. */
  41. public function __construct( $post_type ) {
  42. $this->post_type = $post_type;
  43. $this->namespace = 'wp/v2';
  44. $obj = get_post_type_object( $post_type );
  45. $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
  46. $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type );
  47. }
  48. /**
  49. * Registers the routes for the objects of the controller.
  50. *
  51. * @since 4.7.0
  52. * @access public
  53. *
  54. * @see register_rest_route()
  55. */
  56. public function register_routes() {
  57. register_rest_route( $this->namespace, '/' . $this->rest_base, array(
  58. array(
  59. 'methods' => WP_REST_Server::READABLE,
  60. 'callback' => array( $this, 'get_items' ),
  61. 'permission_callback' => array( $this, 'get_items_permissions_check' ),
  62. 'args' => $this->get_collection_params(),
  63. ),
  64. array(
  65. 'methods' => WP_REST_Server::CREATABLE,
  66. 'callback' => array( $this, 'create_item' ),
  67. 'permission_callback' => array( $this, 'create_item_permissions_check' ),
  68. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
  69. ),
  70. 'schema' => array( $this, 'get_public_item_schema' ),
  71. ) );
  72. $schema = $this->get_item_schema();
  73. $get_item_args = array(
  74. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  75. );
  76. if ( isset( $schema['properties']['password'] ) ) {
  77. $get_item_args['password'] = array(
  78. 'description' => __( 'The password for the post if it is password protected.' ),
  79. 'type' => 'string',
  80. );
  81. }
  82. register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
  83. 'args' => array(
  84. 'id' => array(
  85. 'description' => __( 'Unique identifier for the object.' ),
  86. 'type' => 'integer',
  87. ),
  88. ),
  89. array(
  90. 'methods' => WP_REST_Server::READABLE,
  91. 'callback' => array( $this, 'get_item' ),
  92. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  93. 'args' => $get_item_args,
  94. ),
  95. array(
  96. 'methods' => WP_REST_Server::EDITABLE,
  97. 'callback' => array( $this, 'update_item' ),
  98. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  99. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  100. ),
  101. array(
  102. 'methods' => WP_REST_Server::DELETABLE,
  103. 'callback' => array( $this, 'delete_item' ),
  104. 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  105. 'args' => array(
  106. 'force' => array(
  107. 'type' => 'boolean',
  108. 'default' => false,
  109. 'description' => __( 'Whether to bypass trash and force deletion.' ),
  110. ),
  111. ),
  112. ),
  113. 'schema' => array( $this, 'get_public_item_schema' ),
  114. ) );
  115. }
  116. /**
  117. * Checks if a given request has access to read posts.
  118. *
  119. * @since 4.7.0
  120. * @access public
  121. *
  122. * @param WP_REST_Request $request Full details about the request.
  123. * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
  124. */
  125. public function get_items_permissions_check( $request ) {
  126. $post_type = get_post_type_object( $this->post_type );
  127. if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) {
  128. 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() ) );
  129. }
  130. return true;
  131. }
  132. /**
  133. * Retrieves a collection of posts.
  134. *
  135. * @since 4.7.0
  136. * @access public
  137. *
  138. * @param WP_REST_Request $request Full details about the request.
  139. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  140. */
  141. public function get_items( $request ) {
  142. // Ensure a search string is set in case the orderby is set to 'relevance'.
  143. if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) {
  144. return new WP_Error( 'rest_no_search_term_defined', __( 'You need to define a search term to order by relevance.' ), array( 'status' => 400 ) );
  145. }
  146. // Ensure an include parameter is set in case the orderby is set to 'include'.
  147. if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) {
  148. return new WP_Error( 'rest_orderby_include_missing_include', sprintf( __( 'Missing parameter(s): %s' ), 'include' ), array( 'status' => 400 ) );
  149. }
  150. // Retrieve the list of registered collection query parameters.
  151. $registered = $this->get_collection_params();
  152. $args = array();
  153. /*
  154. * This array defines mappings between public API query parameters whose
  155. * values are accepted as-passed, and their internal WP_Query parameter
  156. * name equivalents (some are the same). Only values which are also
  157. * present in $registered will be set.
  158. */
  159. $parameter_mappings = array(
  160. 'author' => 'author__in',
  161. 'author_exclude' => 'author__not_in',
  162. 'exclude' => 'post__not_in',
  163. 'include' => 'post__in',
  164. 'menu_order' => 'menu_order',
  165. 'offset' => 'offset',
  166. 'order' => 'order',
  167. 'orderby' => 'orderby',
  168. 'page' => 'paged',
  169. 'parent' => 'post_parent__in',
  170. 'parent_exclude' => 'post_parent__not_in',
  171. 'search' => 's',
  172. 'slug' => 'post_name__in',
  173. 'status' => 'post_status',
  174. );
  175. /*
  176. * For each known parameter which is both registered and present in the request,
  177. * set the parameter's value on the query $args.
  178. */
  179. foreach ( $parameter_mappings as $api_param => $wp_param ) {
  180. if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
  181. $args[ $wp_param ] = $request[ $api_param ];
  182. }
  183. }
  184. // Check for & assign any parameters which require special handling or setting.
  185. $args['date_query'] = array();
  186. // Set before into date query. Date query must be specified as an array of an array.
  187. if ( isset( $registered['before'], $request['before'] ) ) {
  188. $args['date_query'][0]['before'] = $request['before'];
  189. }
  190. // Set after into date query. Date query must be specified as an array of an array.
  191. if ( isset( $registered['after'], $request['after'] ) ) {
  192. $args['date_query'][0]['after'] = $request['after'];
  193. }
  194. // Ensure our per_page parameter overrides any provided posts_per_page filter.
  195. if ( isset( $registered['per_page'] ) ) {
  196. $args['posts_per_page'] = $request['per_page'];
  197. }
  198. if ( isset( $registered['sticky'], $request['sticky'] ) ) {
  199. $sticky_posts = get_option( 'sticky_posts', array() );
  200. if ( ! is_array( $sticky_posts ) ) {
  201. $sticky_posts = array();
  202. }
  203. if ( $request['sticky'] ) {
  204. /*
  205. * As post__in will be used to only get sticky posts,
  206. * we have to support the case where post__in was already
  207. * specified.
  208. */
  209. $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts;
  210. /*
  211. * If we intersected, but there are no post ids in common,
  212. * WP_Query won't return "no posts" for post__in = array()
  213. * so we have to fake it a bit.
  214. */
  215. if ( ! $args['post__in'] ) {
  216. $args['post__in'] = array( 0 );
  217. }
  218. } elseif ( $sticky_posts ) {
  219. /*
  220. * As post___not_in will be used to only get posts that
  221. * are not sticky, we have to support the case where post__not_in
  222. * was already specified.
  223. */
  224. $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts );
  225. }
  226. }
  227. // Force the post_type argument, since it's not a user input variable.
  228. $args['post_type'] = $this->post_type;
  229. /**
  230. * Filters the query arguments for a request.
  231. *
  232. * Enables adding extra arguments or setting defaults for a post collection request.
  233. *
  234. * @since 4.7.0
  235. *
  236. * @link https://developer.wordpress.org/reference/classes/wp_query/
  237. *
  238. * @param array $args Key value array of query var to query value.
  239. * @param WP_REST_Request $request The request used.
  240. */
  241. $args = apply_filters( "rest_{$this->post_type}_query", $args, $request );
  242. $query_args = $this->prepare_items_query( $args, $request );
  243. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  244. foreach ( $taxonomies as $taxonomy ) {
  245. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  246. $tax_exclude = $base . '_exclude';
  247. if ( ! empty( $request[ $base ] ) ) {
  248. $query_args['tax_query'][] = array(
  249. 'taxonomy' => $taxonomy->name,
  250. 'field' => 'term_id',
  251. 'terms' => $request[ $base ],
  252. 'include_children' => false,
  253. );
  254. }
  255. if ( ! empty( $request[ $tax_exclude ] ) ) {
  256. $query_args['tax_query'][] = array(
  257. 'taxonomy' => $taxonomy->name,
  258. 'field' => 'term_id',
  259. 'terms' => $request[ $tax_exclude ],
  260. 'include_children' => false,
  261. 'operator' => 'NOT IN',
  262. );
  263. }
  264. }
  265. $posts_query = new WP_Query();
  266. $query_result = $posts_query->query( $query_args );
  267. // Allow access to all password protected posts if the context is edit.
  268. if ( 'edit' === $request['context'] ) {
  269. add_filter( 'post_password_required', '__return_false' );
  270. }
  271. $posts = array();
  272. foreach ( $query_result as $post ) {
  273. if ( ! $this->check_read_permission( $post ) ) {
  274. continue;
  275. }
  276. $data = $this->prepare_item_for_response( $post, $request );
  277. $posts[] = $this->prepare_response_for_collection( $data );
  278. }
  279. // Reset filter.
  280. if ( 'edit' === $request['context'] ) {
  281. remove_filter( 'post_password_required', '__return_false' );
  282. }
  283. $page = (int) $query_args['paged'];
  284. $total_posts = $posts_query->found_posts;
  285. if ( $total_posts < 1 ) {
  286. // Out-of-bounds, run the query again without LIMIT for total count.
  287. unset( $query_args['paged'] );
  288. $count_query = new WP_Query();
  289. $count_query->query( $query_args );
  290. $total_posts = $count_query->found_posts;
  291. }
  292. $max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] );
  293. $response = rest_ensure_response( $posts );
  294. $response->header( 'X-WP-Total', (int) $total_posts );
  295. $response->header( 'X-WP-TotalPages', (int) $max_pages );
  296. $request_params = $request->get_query_params();
  297. $base = add_query_arg( $request_params, rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) );
  298. if ( $page > 1 ) {
  299. $prev_page = $page - 1;
  300. if ( $prev_page > $max_pages ) {
  301. $prev_page = $max_pages;
  302. }
  303. $prev_link = add_query_arg( 'page', $prev_page, $base );
  304. $response->link_header( 'prev', $prev_link );
  305. }
  306. if ( $max_pages > $page ) {
  307. $next_page = $page + 1;
  308. $next_link = add_query_arg( 'page', $next_page, $base );
  309. $response->link_header( 'next', $next_link );
  310. }
  311. return $response;
  312. }
  313. /**
  314. * Get the post, if the ID is valid.
  315. *
  316. * @since 4.7.2
  317. *
  318. * @param int $id Supplied ID.
  319. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise.
  320. */
  321. protected function get_post( $id ) {
  322. $error = new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) );
  323. if ( (int) $id <= 0 ) {
  324. return $error;
  325. }
  326. $post = get_post( (int) $id );
  327. if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
  328. return $error;
  329. }
  330. return $post;
  331. }
  332. /**
  333. * Checks if a given request has access to read a post.
  334. *
  335. * @since 4.7.0
  336. * @access public
  337. *
  338. * @param WP_REST_Request $request Full details about the request.
  339. * @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise.
  340. */
  341. public function get_item_permissions_check( $request ) {
  342. $post = $this->get_post( $request['id'] );
  343. if ( is_wp_error( $post ) ) {
  344. return $post;
  345. }
  346. if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
  347. return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
  348. }
  349. if ( $post && ! empty( $request['password'] ) ) {
  350. // Check post password, and return error if invalid.
  351. if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
  352. return new WP_Error( 'rest_post_incorrect_password', __( 'Incorrect post password.' ), array( 'status' => 403 ) );
  353. }
  354. }
  355. // Allow access to all password protected posts if the context is edit.
  356. if ( 'edit' === $request['context'] ) {
  357. add_filter( 'post_password_required', '__return_false' );
  358. }
  359. if ( $post ) {
  360. return $this->check_read_permission( $post );
  361. }
  362. return true;
  363. }
  364. /**
  365. * Checks if the user can access password-protected content.
  366. *
  367. * This method determines whether we need to override the regular password
  368. * check in core with a filter.
  369. *
  370. * @since 4.7.0
  371. * @access public
  372. *
  373. * @param WP_Post $post Post to check against.
  374. * @param WP_REST_Request $request Request data to check.
  375. * @return bool True if the user can access password-protected content, otherwise false.
  376. */
  377. public function can_access_password_content( $post, $request ) {
  378. if ( empty( $post->post_password ) ) {
  379. // No filter required.
  380. return false;
  381. }
  382. // Edit context always gets access to password-protected posts.
  383. if ( 'edit' === $request['context'] ) {
  384. return true;
  385. }
  386. // No password, no auth.
  387. if ( empty( $request['password'] ) ) {
  388. return false;
  389. }
  390. // Double-check the request password.
  391. return hash_equals( $post->post_password, $request['password'] );
  392. }
  393. /**
  394. * Retrieves a single post.
  395. *
  396. * @since 4.7.0
  397. * @access public
  398. *
  399. * @param WP_REST_Request $request Full details about the request.
  400. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  401. */
  402. public function get_item( $request ) {
  403. $post = $this->get_post( $request['id'] );
  404. if ( is_wp_error( $post ) ) {
  405. return $post;
  406. }
  407. $data = $this->prepare_item_for_response( $post, $request );
  408. $response = rest_ensure_response( $data );
  409. if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) {
  410. $response->link_header( 'alternate', get_permalink( $post->ID ), array( 'type' => 'text/html' ) );
  411. }
  412. return $response;
  413. }
  414. /**
  415. * Checks if a given request has access to create a post.
  416. *
  417. * @since 4.7.0
  418. * @access public
  419. *
  420. * @param WP_REST_Request $request Full details about the request.
  421. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise.
  422. */
  423. public function create_item_permissions_check( $request ) {
  424. if ( ! empty( $request['id'] ) ) {
  425. return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
  426. }
  427. $post_type = get_post_type_object( $this->post_type );
  428. if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  429. 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() ) );
  430. }
  431. if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  432. return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
  433. }
  434. if ( ! current_user_can( $post_type->cap->create_posts ) ) {
  435. return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) );
  436. }
  437. if ( ! $this->check_assign_terms_permission( $request ) ) {
  438. return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
  439. }
  440. return true;
  441. }
  442. /**
  443. * Creates a single post.
  444. *
  445. * @since 4.7.0
  446. * @access public
  447. *
  448. * @param WP_REST_Request $request Full details about the request.
  449. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  450. */
  451. public function create_item( $request ) {
  452. if ( ! empty( $request['id'] ) ) {
  453. return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) );
  454. }
  455. $prepared_post = $this->prepare_item_for_database( $request );
  456. if ( is_wp_error( $prepared_post ) ) {
  457. return $prepared_post;
  458. }
  459. $prepared_post->post_type = $this->post_type;
  460. $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true );
  461. if ( is_wp_error( $post_id ) ) {
  462. if ( 'db_insert_error' === $post_id->get_error_code() ) {
  463. $post_id->add_data( array( 'status' => 500 ) );
  464. } else {
  465. $post_id->add_data( array( 'status' => 400 ) );
  466. }
  467. return $post_id;
  468. }
  469. $post = get_post( $post_id );
  470. /**
  471. * Fires after a single post is created or updated via the REST API.
  472. *
  473. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  474. *
  475. * @since 4.7.0
  476. *
  477. * @param WP_Post $post Inserted or updated post object.
  478. * @param WP_REST_Request $request Request object.
  479. * @param bool $creating True when creating a post, false when updating.
  480. */
  481. do_action( "rest_insert_{$this->post_type}", $post, $request, true );
  482. $schema = $this->get_item_schema();
  483. if ( ! empty( $schema['properties']['sticky'] ) ) {
  484. if ( ! empty( $request['sticky'] ) ) {
  485. stick_post( $post_id );
  486. } else {
  487. unstick_post( $post_id );
  488. }
  489. }
  490. if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
  491. $this->handle_featured_media( $request['featured_media'], $post_id );
  492. }
  493. if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
  494. set_post_format( $post, $request['format'] );
  495. }
  496. if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
  497. $this->handle_template( $request['template'], $post_id );
  498. }
  499. $terms_update = $this->handle_terms( $post_id, $request );
  500. if ( is_wp_error( $terms_update ) ) {
  501. return $terms_update;
  502. }
  503. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  504. $meta_update = $this->meta->update_value( $request['meta'], $post_id );
  505. if ( is_wp_error( $meta_update ) ) {
  506. return $meta_update;
  507. }
  508. }
  509. $post = get_post( $post_id );
  510. $fields_update = $this->update_additional_fields_for_object( $post, $request );
  511. if ( is_wp_error( $fields_update ) ) {
  512. return $fields_update;
  513. }
  514. $request->set_param( 'context', 'edit' );
  515. $response = $this->prepare_item_for_response( $post, $request );
  516. $response = rest_ensure_response( $response );
  517. $response->set_status( 201 );
  518. $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $post_id ) ) );
  519. return $response;
  520. }
  521. /**
  522. * Checks if a given request has access to update a post.
  523. *
  524. * @since 4.7.0
  525. * @access public
  526. *
  527. * @param WP_REST_Request $request Full details about the request.
  528. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise.
  529. */
  530. public function update_item_permissions_check( $request ) {
  531. $post = $this->get_post( $request['id'] );
  532. if ( is_wp_error( $post ) ) {
  533. return $post;
  534. }
  535. $post_type = get_post_type_object( $this->post_type );
  536. if ( $post && ! $this->check_update_permission( $post ) ) {
  537. return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
  538. }
  539. if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  540. 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() ) );
  541. }
  542. if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) ) {
  543. return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) );
  544. }
  545. if ( ! $this->check_assign_terms_permission( $request ) ) {
  546. return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) );
  547. }
  548. return true;
  549. }
  550. /**
  551. * Updates a single post.
  552. *
  553. * @since 4.7.0
  554. * @access public
  555. *
  556. * @param WP_REST_Request $request Full details about the request.
  557. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  558. */
  559. public function update_item( $request ) {
  560. $valid_check = $this->get_post( $request['id'] );
  561. if ( is_wp_error( $valid_check ) ) {
  562. return $valid_check;
  563. }
  564. $post = $this->prepare_item_for_database( $request );
  565. if ( is_wp_error( $post ) ) {
  566. return $post;
  567. }
  568. // convert the post object to an array, otherwise wp_update_post will expect non-escaped input.
  569. $post_id = wp_update_post( wp_slash( (array) $post ), true );
  570. if ( is_wp_error( $post_id ) ) {
  571. if ( 'db_update_error' === $post_id->get_error_code() ) {
  572. $post_id->add_data( array( 'status' => 500 ) );
  573. } else {
  574. $post_id->add_data( array( 'status' => 400 ) );
  575. }
  576. return $post_id;
  577. }
  578. $post = get_post( $post_id );
  579. /* This action is documented in lib/endpoints/class-wp-rest-controller.php */
  580. do_action( "rest_insert_{$this->post_type}", $post, $request, false );
  581. $schema = $this->get_item_schema();
  582. if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) {
  583. set_post_format( $post, $request['format'] );
  584. }
  585. if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) {
  586. $this->handle_featured_media( $request['featured_media'], $post_id );
  587. }
  588. if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) {
  589. if ( ! empty( $request['sticky'] ) ) {
  590. stick_post( $post_id );
  591. } else {
  592. unstick_post( $post_id );
  593. }
  594. }
  595. if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) {
  596. $this->handle_template( $request['template'], $post->ID );
  597. }
  598. $terms_update = $this->handle_terms( $post->ID, $request );
  599. if ( is_wp_error( $terms_update ) ) {
  600. return $terms_update;
  601. }
  602. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  603. $meta_update = $this->meta->update_value( $request['meta'], $post->ID );
  604. if ( is_wp_error( $meta_update ) ) {
  605. return $meta_update;
  606. }
  607. }
  608. $post = get_post( $post_id );
  609. $fields_update = $this->update_additional_fields_for_object( $post, $request );
  610. if ( is_wp_error( $fields_update ) ) {
  611. return $fields_update;
  612. }
  613. $request->set_param( 'context', 'edit' );
  614. $response = $this->prepare_item_for_response( $post, $request );
  615. return rest_ensure_response( $response );
  616. }
  617. /**
  618. * Checks if a given request has access to delete a post.
  619. *
  620. * @since 4.7.0
  621. * @access public
  622. *
  623. * @param WP_REST_Request $request Full details about the request.
  624. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise.
  625. */
  626. public function delete_item_permissions_check( $request ) {
  627. $post = $this->get_post( $request['id'] );
  628. if ( is_wp_error( $post ) ) {
  629. return $post;
  630. }
  631. if ( $post && ! $this->check_delete_permission( $post ) ) {
  632. return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
  633. }
  634. return true;
  635. }
  636. /**
  637. * Deletes a single post.
  638. *
  639. * @since 4.7.0
  640. * @access public
  641. *
  642. * @param WP_REST_Request $request Full details about the request.
  643. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  644. */
  645. public function delete_item( $request ) {
  646. $post = $this->get_post( $request['id'] );
  647. if ( is_wp_error( $post ) ) {
  648. return $post;
  649. }
  650. $id = $post->ID;
  651. $force = (bool) $request['force'];
  652. $supports_trash = ( EMPTY_TRASH_DAYS > 0 );
  653. if ( 'attachment' === $post->post_type ) {
  654. $supports_trash = $supports_trash && MEDIA_TRASH;
  655. }
  656. /**
  657. * Filters whether a post is trashable.
  658. *
  659. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  660. *
  661. * Pass false to disable trash support for the post.
  662. *
  663. * @since 4.7.0
  664. *
  665. * @param bool $supports_trash Whether the post type support trashing.
  666. * @param WP_Post $post The Post object being considered for trashing support.
  667. */
  668. $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post );
  669. if ( ! $this->check_delete_permission( $post ) ) {
  670. return new WP_Error( 'rest_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) );
  671. }
  672. $request->set_param( 'context', 'edit' );
  673. // If we're forcing, then delete permanently.
  674. if ( $force ) {
  675. $previous = $this->prepare_item_for_response( $post, $request );
  676. $result = wp_delete_post( $id, true );
  677. $response = new WP_REST_Response();
  678. $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data() ) );
  679. } else {
  680. // If we don't support trashing for this type, error out.
  681. if ( ! $supports_trash ) {
  682. return new WP_Error( 'rest_trash_not_supported', __( 'The post does not support trashing. Set force=true to delete.' ), array( 'status' => 501 ) );
  683. }
  684. // Otherwise, only trash if we haven't already.
  685. if ( 'trash' === $post->post_status ) {
  686. return new WP_Error( 'rest_already_trashed', __( 'The post has already been deleted.' ), array( 'status' => 410 ) );
  687. }
  688. // (Note that internally this falls through to `wp_delete_post` if
  689. // the trash is disabled.)
  690. $result = wp_trash_post( $id );
  691. $post = get_post( $id );
  692. $response = $this->prepare_item_for_response( $post, $request );
  693. }
  694. if ( ! $result ) {
  695. return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) );
  696. }
  697. /**
  698. * Fires immediately after a single post is deleted or trashed via the REST API.
  699. *
  700. * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  701. *
  702. * @since 4.7.0
  703. *
  704. * @param object $post The deleted or trashed post.
  705. * @param WP_REST_Response $response The response data.
  706. * @param WP_REST_Request $request The request sent to the API.
  707. */
  708. do_action( "rest_delete_{$this->post_type}", $post, $response, $request );
  709. return $response;
  710. }
  711. /**
  712. * Determines the allowed query_vars for a get_items() response and prepares
  713. * them for WP_Query.
  714. *
  715. * @since 4.7.0
  716. * @access protected
  717. *
  718. * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array.
  719. * @param WP_REST_Request $request Optional. Full details about the request.
  720. * @return array Items query arguments.
  721. */
  722. protected function prepare_items_query( $prepared_args = array(), $request = null ) {
  723. $query_args = array();
  724. foreach ( $prepared_args as $key => $value ) {
  725. /**
  726. * Filters the query_vars used in get_items() for the constructed query.
  727. *
  728. * The dynamic portion of the hook name, `$key`, refers to the query_var key.
  729. *
  730. * @since 4.7.0
  731. *
  732. * @param string $value The query_var value.
  733. */
  734. $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value );
  735. }
  736. if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) {
  737. $query_args['ignore_sticky_posts'] = true;
  738. }
  739. // Map to proper WP_Query orderby param.
  740. if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) {
  741. $orderby_mappings = array(
  742. 'id' => 'ID',
  743. 'include' => 'post__in',
  744. 'slug' => 'post_name',
  745. );
  746. if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
  747. $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
  748. }
  749. }
  750. return $query_args;
  751. }
  752. /**
  753. * Checks the post_date_gmt or modified_gmt and prepare any post or
  754. * modified date for single post output.
  755. *
  756. * @since 4.7.0
  757. * @access protected
  758. *
  759. * @param string $date_gmt GMT publication time.
  760. * @param string|null $date Optional. Local publication time. Default null.
  761. * @return string|null ISO8601/RFC3339 formatted datetime.
  762. */
  763. protected function prepare_date_response( $date_gmt, $date = null ) {
  764. // Use the date if passed.
  765. if ( isset( $date ) ) {
  766. return mysql_to_rfc3339( $date );
  767. }
  768. // Return null if $date_gmt is empty/zeros.
  769. if ( '0000-00-00 00:00:00' === $date_gmt ) {
  770. return null;
  771. }
  772. // Return the formatted datetime.
  773. return mysql_to_rfc3339( $date_gmt );
  774. }
  775. /**
  776. * Prepares a single post for create or update.
  777. *
  778. * @since 4.7.0
  779. * @access protected
  780. *
  781. * @param WP_REST_Request $request Request object.
  782. * @return stdClass|WP_Error Post object or WP_Error.
  783. */
  784. protected function prepare_item_for_database( $request ) {
  785. $prepared_post = new stdClass;
  786. // Post ID.
  787. if ( isset( $request['id'] ) ) {
  788. $existing_post = $this->get_post( $request['id'] );
  789. if ( is_wp_error( $existing_post ) ) {
  790. return $existing_post;
  791. }
  792. $prepared_post->ID = $existing_post->ID;
  793. }
  794. $schema = $this->get_item_schema();
  795. // Post title.
  796. if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
  797. if ( is_string( $request['title'] ) ) {
  798. $prepared_post->post_title = $request['title'];
  799. } elseif ( ! empty( $request['title']['raw'] ) ) {
  800. $prepared_post->post_title = $request['title']['raw'];
  801. }
  802. }
  803. // Post content.
  804. if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) {
  805. if ( is_string( $request['content'] ) ) {
  806. $prepared_post->post_content = $request['content'];
  807. } elseif ( isset( $request['content']['raw'] ) ) {
  808. $prepared_post->post_content = $request['content']['raw'];
  809. }
  810. }
  811. // Post excerpt.
  812. if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) {
  813. if ( is_string( $request['excerpt'] ) ) {
  814. $prepared_post->post_excerpt = $request['excerpt'];
  815. } elseif ( isset( $request['excerpt']['raw'] ) ) {
  816. $prepared_post->post_excerpt = $request['excerpt']['raw'];
  817. }
  818. }
  819. // Post type.
  820. if ( empty( $request['id'] ) ) {
  821. // Creating new post, use default type for the controller.
  822. $prepared_post->post_type = $this->post_type;
  823. } else {
  824. // Updating a post, use previous type.
  825. $prepared_post->post_type = get_post_type( $request['id'] );
  826. }
  827. $post_type = get_post_type_object( $prepared_post->post_type );
  828. // Post status.
  829. if ( ! empty( $schema['properties']['status'] ) && isset( $request['status'] ) ) {
  830. $status = $this->handle_status_param( $request['status'], $post_type );
  831. if ( is_wp_error( $status ) ) {
  832. return $status;
  833. }
  834. $prepared_post->post_status = $status;
  835. }
  836. // Post date.
  837. if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) {
  838. $date_data = rest_get_date_with_gmt( $request['date'] );
  839. if ( ! empty( $date_data ) ) {
  840. list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
  841. $prepared_post->edit_date = true;
  842. }
  843. } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) {
  844. $date_data = rest_get_date_with_gmt( $request['date_gmt'], true );
  845. if ( ! empty( $date_data ) ) {
  846. list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data;
  847. $prepared_post->edit_date = true;
  848. }
  849. }
  850. // Post slug.
  851. if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) {
  852. $prepared_post->post_name = $request['slug'];
  853. }
  854. // Author.
  855. if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) {
  856. $post_author = (int) $request['author'];
  857. if ( get_current_user_id() !== $post_author ) {
  858. $user_obj = get_userdata( $post_author );
  859. if ( ! $user_obj ) {
  860. return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) );
  861. }
  862. }
  863. $prepared_post->post_author = $post_author;
  864. }
  865. // Post password.
  866. if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) {
  867. $prepared_post->post_password = $request['password'];
  868. if ( '' !== $request['password'] ) {
  869. if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
  870. return new WP_Error( 'rest_invalid_field', __( 'A post can not be sticky and have a password.' ), array( 'status' => 400 ) );
  871. }
  872. if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) {
  873. return new WP_Error( 'rest_invalid_field', __( 'A sticky post can not be password protected.' ), array( 'status' => 400 ) );
  874. }
  875. }
  876. }
  877. if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) {
  878. if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) {
  879. return new WP_Error( 'rest_invalid_field', __( 'A password protected post can not be set to sticky.' ), array( 'status' => 400 ) );
  880. }
  881. }
  882. // Parent.
  883. if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) {
  884. if ( 0 === (int) $request['parent'] ) {
  885. $prepared_post->post_parent = 0;
  886. } else {
  887. $parent = get_post( (int) $request['parent'] );
  888. if ( empty( $parent ) ) {
  889. return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) );
  890. }
  891. $prepared_post->post_parent = (int) $parent->ID;
  892. }
  893. }
  894. // Menu order.
  895. if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) {
  896. $prepared_post->menu_order = (int) $request['menu_order'];
  897. }
  898. // Comment status.
  899. if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) {
  900. $prepared_post->comment_status = $request['comment_status'];
  901. }
  902. // Ping status.
  903. if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) {
  904. $prepared_post->ping_status = $request['ping_status'];
  905. }
  906. /**
  907. * Filters a post before it is inserted via the REST API.
  908. *
  909. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  910. *
  911. * @since 4.7.0
  912. *
  913. * @param stdClass $prepared_post An object representing a single post prepared
  914. * for inserting or updating the database.
  915. * @param WP_REST_Request $request Request object.
  916. */
  917. return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request );
  918. }
  919. /**
  920. * Determines validity and normalizes the given status parameter.
  921. *
  922. * @since 4.7.0
  923. * @access protected
  924. *
  925. * @param string $post_status Post status.
  926. * @param object $post_type Post type.
  927. * @return string|WP_Error Post status or WP_Error if lacking the proper permission.
  928. */
  929. protected function handle_status_param( $post_status, $post_type ) {
  930. switch ( $post_status ) {
  931. case 'draft':
  932. case 'pending':
  933. break;
  934. case 'private':
  935. if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
  936. 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() ) );
  937. }
  938. break;
  939. case 'publish':
  940. case 'future':
  941. if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
  942. 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() ) );
  943. }
  944. break;
  945. default:
  946. if ( ! get_post_status_object( $post_status ) ) {
  947. $post_status = 'draft';
  948. }
  949. break;
  950. }
  951. return $post_status;
  952. }
  953. /**
  954. * Determines the featured media based on a request param.
  955. *
  956. * @since 4.7.0
  957. * @access protected
  958. *
  959. * @param int $featured_media Featured Media ID.
  960. * @param int $post_id Post ID.
  961. * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error.
  962. */
  963. protected function handle_featured_media( $featured_media, $post_id ) {
  964. $featured_media = (int) $featured_media;
  965. if ( $featured_media ) {
  966. $result = set_post_thumbnail( $post_id, $featured_media );
  967. if ( $result ) {
  968. return true;
  969. } else {
  970. return new WP_Error( 'rest_invalid_featured_media', __( 'Invalid featured media ID.' ), array( 'status' => 400 ) );
  971. }
  972. } else {
  973. return delete_post_thumbnail( $post_id );
  974. }
  975. }
  976. /**
  977. * Sets the template for a post.
  978. *
  979. * @since 4.7.0
  980. * @access public
  981. *
  982. * @param string $template Page template filename.
  983. * @param integer $post_id Post ID.
  984. */
  985. public function handle_template( $template, $post_id ) {
  986. if ( in_array( $template, array_keys( wp_get_theme()->get_page_templates( get_post( $post_id ) ) ), true ) ) {
  987. update_post_meta( $post_id, '_wp_page_template', $template );
  988. } else {
  989. update_post_meta( $post_id, '_wp_page_template', '' );
  990. }
  991. }
  992. /**
  993. * Updates the post's terms from a REST request.
  994. *
  995. * @since 4.7.0
  996. * @access protected
  997. *
  998. * @param int $post_id The post ID to update the terms form.
  999. * @param WP_REST_Request $request The request object with post and terms data.
  1000. * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null.
  1001. */
  1002. protected function handle_terms( $post_id, $request ) {
  1003. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1004. foreach ( $taxonomies as $taxonomy ) {
  1005. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1006. if ( ! isset( $request[ $base ] ) ) {
  1007. continue;
  1008. }
  1009. $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name );
  1010. if ( is_wp_error( $result ) ) {
  1011. return $result;
  1012. }
  1013. }
  1014. }
  1015. /**
  1016. * Checks whether current user can assign all terms sent with the current request.
  1017. *
  1018. * @since 4.7.0
  1019. *
  1020. * @param WP_REST_Request $request The request object with post and terms data.
  1021. * @return bool Whether the current user can assign the provided terms.
  1022. */
  1023. protected function check_assign_terms_permission( $request ) {
  1024. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1025. foreach ( $taxonomies as $taxonomy ) {
  1026. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1027. if ( ! isset( $request[ $base ] ) ) {
  1028. continue;
  1029. }
  1030. foreach ( $request[ $base ] as $term_id ) {
  1031. // Invalid terms will be rejected later.
  1032. if ( ! get_term( $term_id, $taxonomy->name ) ) {
  1033. continue;
  1034. }
  1035. if ( ! current_user_can( 'assign_term', (int) $term_id ) ) {
  1036. return false;
  1037. }
  1038. }
  1039. }
  1040. return true;
  1041. }
  1042. /**
  1043. * Checks if a given post type can be viewed or managed.
  1044. *
  1045. * @since 4.7.0
  1046. * @access protected
  1047. *
  1048. * @param object|string $post_type Post type name or object.
  1049. * @return bool Whether the post type is allowed in REST.
  1050. */
  1051. protected function check_is_post_type_allowed( $post_type ) {
  1052. if ( ! is_object( $post_type ) ) {
  1053. $post_type = get_post_type_object( $post_type );
  1054. }
  1055. if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) {
  1056. return true;
  1057. }
  1058. return false;
  1059. }
  1060. /**
  1061. * Checks if a post can be read.
  1062. *
  1063. * Correctly handles posts with the inherit status.
  1064. *
  1065. * @since 4.7.0
  1066. * @access public
  1067. *
  1068. * @param object $post Post object.
  1069. * @return bool Whether the post can be read.
  1070. */
  1071. public function check_read_permission( $post ) {
  1072. $post_type = get_post_type_object( $post->post_type );
  1073. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1074. return false;
  1075. }
  1076. // Is the post readable?
  1077. if ( 'publish' === $post->post_status || current_user_can( $post_type->cap->read_post, $post->ID ) ) {
  1078. return true;
  1079. }
  1080. $post_status_obj = get_post_status_object( $post->post_status );
  1081. if ( $post_status_obj && $post_status_obj->public ) {
  1082. return true;
  1083. }
  1084. // Can we read the parent if we're inheriting?
  1085. if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) {
  1086. $parent = get_post( $post->post_parent );
  1087. return $this->check_read_permission( $parent );
  1088. }
  1089. /*
  1090. * If there isn't a parent, but the status is set to inherit, assume
  1091. * it's published (as per get_post_status()).
  1092. */
  1093. if ( 'inherit' === $post->post_status ) {
  1094. return true;
  1095. }
  1096. return false;
  1097. }
  1098. /**
  1099. * Checks if a post can be edited.
  1100. *
  1101. * @since 4.7.0
  1102. * @access protected
  1103. *
  1104. * @param object $post Post object.
  1105. * @return bool Whether the post can be edited.
  1106. */
  1107. protected function check_update_permission( $post ) {
  1108. $post_type = get_post_type_object( $post->post_type );
  1109. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1110. return false;
  1111. }
  1112. return current_user_can( $post_type->cap->edit_post, $post->ID );
  1113. }
  1114. /**
  1115. * Checks if a post can be created.
  1116. *
  1117. * @since 4.7.0
  1118. * @access protected
  1119. *
  1120. * @param object $post Post object.
  1121. * @return bool Whether the post can be created.
  1122. */
  1123. protected function check_create_permission( $post ) {
  1124. $post_type = get_post_type_object( $post->post_type );
  1125. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1126. return false;
  1127. }
  1128. return current_user_can( $post_type->cap->create_posts );
  1129. }
  1130. /**
  1131. * Checks if a post can be deleted.
  1132. *
  1133. * @since 4.7.0
  1134. * @access protected
  1135. *
  1136. * @param object $post Post object.
  1137. * @return bool Whether the post can be deleted.
  1138. */
  1139. protected function check_delete_permission( $post ) {
  1140. $post_type = get_post_type_object( $post->post_type );
  1141. if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
  1142. return false;
  1143. }
  1144. return current_user_can( $post_type->cap->delete_post, $post->ID );
  1145. }
  1146. /**
  1147. * Prepares a single post output for response.
  1148. *
  1149. * @since 4.7.0
  1150. * @access public
  1151. *
  1152. * @param WP_Post $post Post object.
  1153. * @param WP_REST_Request $request Request object.
  1154. * @return WP_REST_Response Response object.
  1155. */
  1156. public function prepare_item_for_response( $post, $request ) {
  1157. $GLOBALS['post'] = $post;
  1158. setup_postdata( $post );
  1159. $schema = $this->get_item_schema();
  1160. // Base fields for every post.
  1161. $data = array();
  1162. if ( ! empty( $schema['properties']['id'] ) ) {
  1163. $data['id'] = $post->ID;
  1164. }
  1165. if ( ! empty( $schema['properties']['date'] ) ) {
  1166. $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date );
  1167. }
  1168. if ( ! empty( $schema['properties']['date_gmt'] ) ) {
  1169. // For drafts, `post_date_gmt` may not be set, indicating that the
  1170. // date of the draft should be updated each time it is saved (see
  1171. // #38883). In this case, shim the value based on the `post_date`
  1172. // field with the site's timezone offset applied.
  1173. if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
  1174. $post_date_gmt = date( 'Y-m-d H:i:s', strtotime( $post->post_date ) - ( get_option( 'gmt_offset' ) * 3600 ) );
  1175. } else {
  1176. $post_date_gmt = $post->post_date_gmt;
  1177. }
  1178. $data['date_gmt'] = $this->prepare_date_response( $post_date_gmt );
  1179. }
  1180. if ( ! empty( $schema['properties']['guid'] ) ) {
  1181. $data['guid'] = array(
  1182. /** This filter is documented in wp-includes/post-template.php */
  1183. 'rendered' => apply_filters( 'get_the_guid', $post->guid ),
  1184. 'raw' => $post->guid,
  1185. );
  1186. }
  1187. if ( ! empty( $schema['properties']['modified'] ) ) {
  1188. $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified );
  1189. }
  1190. if ( ! empty( $schema['properties']['modified_gmt'] ) ) {
  1191. // For drafts, `post_modified_gmt` may not be set (see
  1192. // `post_date_gmt` comments above). In this case, shim the value
  1193. // based on the `post_modified` field with the site's timezone
  1194. // offset applied.
  1195. if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) {
  1196. $post_modified_gmt = date( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - ( get_option( 'gmt_offset' ) * 3600 ) );
  1197. } else {
  1198. $post_modified_gmt = $post->post_modified_gmt;
  1199. }
  1200. $data['modified_gmt'] = $this->prepare_date_response( $post_modified_gmt );
  1201. }
  1202. if ( ! empty( $schema['properties']['password'] ) ) {
  1203. $data['password'] = $post->post_password;
  1204. }
  1205. if ( ! empty( $schema['properties']['slug'] ) ) {
  1206. $data['slug'] = $post->post_name;
  1207. }
  1208. if ( ! empty( $schema['properties']['status'] ) ) {
  1209. $data['status'] = $post->post_status;
  1210. }
  1211. if ( ! empty( $schema['properties']['type'] ) ) {
  1212. $data['type'] = $post->post_type;
  1213. }
  1214. if ( ! empty( $schema['properties']['link'] ) ) {
  1215. $data['link'] = get_permalink( $post->ID );
  1216. }
  1217. if ( ! empty( $schema['properties']['title'] ) ) {
  1218. add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  1219. $data['title'] = array(
  1220. 'raw' => $post->post_title,
  1221. 'rendered' => get_the_title( $post->ID ),
  1222. );
  1223. remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
  1224. }
  1225. $has_password_filter = false;
  1226. if ( $this->can_access_password_content( $post, $request ) ) {
  1227. // Allow access to the post, permissions already checked before.
  1228. add_filter( 'post_password_required', '__return_false' );
  1229. $has_password_filter = true;
  1230. }
  1231. if ( ! empty( $schema['properties']['content'] ) ) {
  1232. $data['content'] = array(
  1233. 'raw' => $post->post_content,
  1234. /** This filter is documented in wp-includes/post-template.php */
  1235. 'rendered' => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
  1236. 'protected' => (bool) $post->post_password,
  1237. );
  1238. }
  1239. if ( ! empty( $schema['properties']['excerpt'] ) ) {
  1240. /** This filter is documented in wp-includes/post-template.php */
  1241. $excerpt = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
  1242. $data['excerpt'] = array(
  1243. 'raw' => $post->post_excerpt,
  1244. 'rendered' => post_password_required( $post ) ? '' : $excerpt,
  1245. 'protected' => (bool) $post->post_password,
  1246. );
  1247. }
  1248. if ( $has_password_filter ) {
  1249. // Reset filter.
  1250. remove_filter( 'post_password_required', '__return_false' );
  1251. }
  1252. if ( ! empty( $schema['properties']['author'] ) ) {
  1253. $data['author'] = (int) $post->post_author;
  1254. }
  1255. if ( ! empty( $schema['properties']['featured_media'] ) ) {
  1256. $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID );
  1257. }
  1258. if ( ! empty( $schema['properties']['parent'] ) ) {
  1259. $data['parent'] = (int) $post->post_parent;
  1260. }
  1261. if ( ! empty( $schema['properties']['menu_order'] ) ) {
  1262. $data['menu_order'] = (int) $post->menu_order;
  1263. }
  1264. if ( ! empty( $schema['properties']['comment_status'] ) ) {
  1265. $data['comment_status'] = $post->comment_status;
  1266. }
  1267. if ( ! empty( $schema['properties']['ping_status'] ) ) {
  1268. $data['ping_status'] = $post->ping_status;
  1269. }
  1270. if ( ! empty( $schema['properties']['sticky'] ) ) {
  1271. $data['sticky'] = is_sticky( $post->ID );
  1272. }
  1273. if ( ! empty( $schema['properties']['template'] ) ) {
  1274. if ( $template = get_page_template_slug( $post->ID ) ) {
  1275. $data['template'] = $template;
  1276. } else {
  1277. $data['template'] = '';
  1278. }
  1279. }
  1280. if ( ! empty( $schema['properties']['format'] ) ) {
  1281. $data['format'] = get_post_format( $post->ID );
  1282. // Fill in blank post format.
  1283. if ( empty( $data['format'] ) ) {
  1284. $data['format'] = 'standard';
  1285. }
  1286. }
  1287. if ( ! empty( $schema['properties']['meta'] ) ) {
  1288. $data['meta'] = $this->meta->get_value( $post->ID, $request );
  1289. }
  1290. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1291. foreach ( $taxonomies as $taxonomy ) {
  1292. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1293. if ( ! empty( $schema['properties'][ $base ] ) ) {
  1294. $terms = get_the_terms( $post, $taxonomy->name );
  1295. $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
  1296. }
  1297. }
  1298. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  1299. $data = $this->add_additional_fields_to_object( $data, $request );
  1300. $data = $this->filter_response_by_context( $data, $context );
  1301. // Wrap the data in a response object.
  1302. $response = rest_ensure_response( $data );
  1303. $response->add_links( $this->prepare_links( $post ) );
  1304. /**
  1305. * Filters the post data for a response.
  1306. *
  1307. * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
  1308. *
  1309. * @since 4.7.0
  1310. *
  1311. * @param WP_REST_Response $response The response object.
  1312. * @param WP_Post $post Post object.
  1313. * @param WP_REST_Request $request Request object.
  1314. */
  1315. return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request );
  1316. }
  1317. /**
  1318. * Overwrites the default protected title format.
  1319. *
  1320. * By default, WordPress will show password protected posts with a title of
  1321. * "Protected: %s", as the REST API communicates the protected status of a post
  1322. * in a machine readable format, we remove the "Protected: " prefix.
  1323. *
  1324. * @return string Protected title format.
  1325. */
  1326. public function protected_title_format() {
  1327. return '%s';
  1328. }
  1329. /**
  1330. * Prepares links for the request.
  1331. *
  1332. * @since 4.7.0
  1333. * @access protected
  1334. *
  1335. * @param WP_Post $post Post object.
  1336. * @return array Links for the given post.
  1337. */
  1338. protected function prepare_links( $post ) {
  1339. $base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
  1340. // Entity meta.
  1341. $links = array(
  1342. 'self' => array(
  1343. 'href' => rest_url( trailingslashit( $base ) . $post->ID ),
  1344. ),
  1345. 'collection' => array(
  1346. 'href' => rest_url( $base ),
  1347. ),
  1348. 'about' => array(
  1349. 'href' => rest_url( 'wp/v2/types/' . $this->post_type ),
  1350. ),
  1351. );
  1352. if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) )
  1353. && ! empty( $post->post_author ) ) {
  1354. $links['author'] = array(
  1355. 'href' => rest_url( 'wp/v2/users/' . $post->post_author ),
  1356. 'embeddable' => true,
  1357. );
  1358. }
  1359. if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) {
  1360. $replies_url = rest_url( 'wp/v2/comments' );
  1361. $replies_url = add_query_arg( 'post', $post->ID, $replies_url );
  1362. $links['replies'] = array(
  1363. 'href' => $replies_url,
  1364. 'embeddable' => true,
  1365. );
  1366. }
  1367. if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) {
  1368. $links['version-history'] = array(
  1369. 'href' => rest_url( trailingslashit( $base ) . $post->ID . '/revisions' ),
  1370. );
  1371. }
  1372. $post_type_obj = get_post_type_object( $post->post_type );
  1373. if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) {
  1374. $links['up'] = array(
  1375. 'href' => rest_url( trailingslashit( $base ) . (int) $post->post_parent ),
  1376. 'embeddable' => true,
  1377. );
  1378. }
  1379. // If we have a featured media, add that.
  1380. if ( $featured_media = get_post_thumbnail_id( $post->ID ) ) {
  1381. $image_url = rest_url( 'wp/v2/media/' . $featured_media );
  1382. $links['https://api.w.org/featuredmedia'] = array(
  1383. 'href' => $image_url,
  1384. 'embeddable' => true,
  1385. );
  1386. }
  1387. if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) {
  1388. $attachments_url = rest_url( 'wp/v2/media' );
  1389. $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url );
  1390. $links['https://api.w.org/attachment'] = array(
  1391. 'href' => $attachments_url,
  1392. );
  1393. }
  1394. $taxonomies = get_object_taxonomies( $post->post_type );
  1395. if ( ! empty( $taxonomies ) ) {
  1396. $links['https://api.w.org/term'] = array();
  1397. foreach ( $taxonomies as $tax ) {
  1398. $taxonomy_obj = get_taxonomy( $tax );
  1399. // Skip taxonomies that are not public.
  1400. if ( empty( $taxonomy_obj->show_in_rest ) ) {
  1401. continue;
  1402. }
  1403. $tax_base = ! empty( $taxonomy_obj->rest_base ) ? $taxonomy_obj->rest_base : $tax;
  1404. $terms_url = add_query_arg(
  1405. 'post',
  1406. $post->ID,
  1407. rest_url( 'wp/v2/' . $tax_base )
  1408. );
  1409. $links['https://api.w.org/term'][] = array(
  1410. 'href' => $terms_url,
  1411. 'taxonomy' => $tax,
  1412. 'embeddable' => true,
  1413. );
  1414. }
  1415. }
  1416. return $links;
  1417. }
  1418. /**
  1419. * Retrieves the post's schema, conforming to JSON Schema.
  1420. *
  1421. * @since 4.7.0
  1422. * @access public
  1423. *
  1424. * @return array Item schema data.
  1425. */
  1426. public function get_item_schema() {
  1427. $schema = array(
  1428. '$schema' => 'http://json-schema.org/schema#',
  1429. 'title' => $this->post_type,
  1430. 'type' => 'object',
  1431. // Base properties for every Post.
  1432. 'properties' => array(
  1433. 'date' => array(
  1434. 'description' => __( "The date the object was published, in the site's timezone." ),
  1435. 'type' => 'string',
  1436. 'format' => 'date-time',
  1437. 'context' => array( 'view', 'edit', 'embed' ),
  1438. ),
  1439. 'date_gmt' => array(
  1440. 'description' => __( 'The date the object was published, as GMT.' ),
  1441. 'type' => 'string',
  1442. 'format' => 'date-time',
  1443. 'context' => array( 'view', 'edit' ),
  1444. ),
  1445. 'guid' => array(
  1446. 'description' => __( 'The globally unique identifier for the object.' ),
  1447. 'type' => 'object',
  1448. 'context' => array( 'view', 'edit' ),
  1449. 'readonly' => true,
  1450. 'properties' => array(
  1451. 'raw' => array(
  1452. 'description' => __( 'GUID for the object, as it exists in the database.' ),
  1453. 'type' => 'string',
  1454. 'context' => array( 'edit' ),
  1455. 'readonly' => true,
  1456. ),
  1457. 'rendered' => array(
  1458. 'description' => __( 'GUID for the object, transformed for display.' ),
  1459. 'type' => 'string',
  1460. 'context' => array( 'view', 'edit' ),
  1461. 'readonly' => true,
  1462. ),
  1463. ),
  1464. ),
  1465. 'id' => array(
  1466. 'description' => __( 'Unique identifier for the object.' ),
  1467. 'type' => 'integer',
  1468. 'context' => array( 'view', 'edit', 'embed' ),
  1469. 'readonly' => true,
  1470. ),
  1471. 'link' => array(
  1472. 'description' => __( 'URL to the object.' ),
  1473. 'type' => 'string',
  1474. 'format' => 'uri',
  1475. 'context' => array( 'view', 'edit', 'embed' ),
  1476. 'readonly' => true,
  1477. ),
  1478. 'modified' => array(
  1479. 'description' => __( "The date the object was last modified, in the site's timezone." ),
  1480. 'type' => 'string',
  1481. 'format' => 'date-time',
  1482. 'context' => array( 'view', 'edit' ),
  1483. 'readonly' => true,
  1484. ),
  1485. 'modified_gmt' => array(
  1486. 'description' => __( 'The date the object was last modified, as GMT.' ),
  1487. 'type' => 'string',
  1488. 'format' => 'date-time',
  1489. 'context' => array( 'view', 'edit' ),
  1490. 'readonly' => true,
  1491. ),
  1492. 'slug' => array(
  1493. 'description' => __( 'An alphanumeric identifier for the object unique to its type.' ),
  1494. 'type' => 'string',
  1495. 'context' => array( 'view', 'edit', 'embed' ),
  1496. 'arg_options' => array(
  1497. 'sanitize_callback' => array( $this, 'sanitize_slug' ),
  1498. ),
  1499. ),
  1500. 'status' => array(
  1501. 'description' => __( 'A named status for the object.' ),
  1502. 'type' => 'string',
  1503. 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ),
  1504. 'context' => array( 'view', 'edit' ),
  1505. ),
  1506. 'type' => array(
  1507. 'description' => __( 'Type of Post for the object.' ),
  1508. 'type' => 'string',
  1509. 'context' => array( 'view', 'edit', 'embed' ),
  1510. 'readonly' => true,
  1511. ),
  1512. 'password' => array(
  1513. 'description' => __( 'A password to protect access to the content and excerpt.' ),
  1514. 'type' => 'string',
  1515. 'context' => array( 'edit' ),
  1516. ),
  1517. ),
  1518. );
  1519. $post_type_obj = get_post_type_object( $this->post_type );
  1520. if ( $post_type_obj->hierarchical ) {
  1521. $schema['properties']['parent'] = array(
  1522. 'description' => __( 'The ID for the parent of the object.' ),
  1523. 'type' => 'integer',
  1524. 'context' => array( 'view', 'edit' ),
  1525. );
  1526. }
  1527. $post_type_attributes = array(
  1528. 'title',
  1529. 'editor',
  1530. 'author',
  1531. 'excerpt',
  1532. 'thumbnail',
  1533. 'comments',
  1534. 'revisions',
  1535. 'page-attributes',
  1536. 'post-formats',
  1537. 'custom-fields',
  1538. );
  1539. $fixed_schemas = array(
  1540. 'post' => array(
  1541. 'title',
  1542. 'editor',
  1543. 'author',
  1544. 'excerpt',
  1545. 'thumbnail',
  1546. 'comments',
  1547. 'revisions',
  1548. 'post-formats',
  1549. 'custom-fields',
  1550. ),
  1551. 'page' => array(
  1552. 'title',
  1553. 'editor',
  1554. 'author',
  1555. 'excerpt',
  1556. 'thumbnail',
  1557. 'comments',
  1558. 'revisions',
  1559. 'page-attributes',
  1560. 'custom-fields',
  1561. ),
  1562. 'attachment' => array(
  1563. 'title',
  1564. 'author',
  1565. 'comments',
  1566. 'revisions',
  1567. 'custom-fields',
  1568. ),
  1569. );
  1570. foreach ( $post_type_attributes as $attribute ) {
  1571. if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) {
  1572. continue;
  1573. } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) {
  1574. continue;
  1575. }
  1576. switch ( $attribute ) {
  1577. case 'title':
  1578. $schema['properties']['title'] = array(
  1579. 'description' => __( 'The title for the object.' ),
  1580. 'type' => 'object',
  1581. 'context' => array( 'view', 'edit', 'embed' ),
  1582. 'arg_options' => array(
  1583. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
  1584. ),
  1585. 'properties' => array(
  1586. 'raw' => array(
  1587. 'description' => __( 'Title for the object, as it exists in the database.' ),
  1588. 'type' => 'string',
  1589. 'context' => array( 'edit' ),
  1590. ),
  1591. 'rendered' => array(
  1592. 'description' => __( 'HTML title for the object, transformed for display.' ),
  1593. 'type' => 'string',
  1594. 'context' => array( 'view', 'edit', 'embed' ),
  1595. 'readonly' => true,
  1596. ),
  1597. ),
  1598. );
  1599. break;
  1600. case 'editor':
  1601. $schema['properties']['content'] = array(
  1602. 'description' => __( 'The content for the object.' ),
  1603. 'type' => 'object',
  1604. 'context' => array( 'view', 'edit' ),
  1605. 'arg_options' => array(
  1606. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
  1607. ),
  1608. 'properties' => array(
  1609. 'raw' => array(
  1610. 'description' => __( 'Content for the object, as it exists in the database.' ),
  1611. 'type' => 'string',
  1612. 'context' => array( 'edit' ),
  1613. ),
  1614. 'rendered' => array(
  1615. 'description' => __( 'HTML content for the object, transformed for display.' ),
  1616. 'type' => 'string',
  1617. 'context' => array( 'view', 'edit' ),
  1618. 'readonly' => true,
  1619. ),
  1620. 'protected' => array(
  1621. 'description' => __( 'Whether the content is protected with a password.' ),
  1622. 'type' => 'boolean',
  1623. 'context' => array( 'view', 'edit', 'embed' ),
  1624. 'readonly' => true,
  1625. ),
  1626. ),
  1627. );
  1628. break;
  1629. case 'author':
  1630. $schema['properties']['author'] = array(
  1631. 'description' => __( 'The ID for the author of the object.' ),
  1632. 'type' => 'integer',
  1633. 'context' => array( 'view', 'edit', 'embed' ),
  1634. );
  1635. break;
  1636. case 'excerpt':
  1637. $schema['properties']['excerpt'] = array(
  1638. 'description' => __( 'The excerpt for the object.' ),
  1639. 'type' => 'object',
  1640. 'context' => array( 'view', 'edit', 'embed' ),
  1641. 'arg_options' => array(
  1642. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
  1643. ),
  1644. 'properties' => array(
  1645. 'raw' => array(
  1646. 'description' => __( 'Excerpt for the object, as it exists in the database.' ),
  1647. 'type' => 'string',
  1648. 'context' => array( 'edit' ),
  1649. ),
  1650. 'rendered' => array(
  1651. 'description' => __( 'HTML excerpt for the object, transformed for display.' ),
  1652. 'type' => 'string',
  1653. 'context' => array( 'view', 'edit', 'embed' ),
  1654. 'readonly' => true,
  1655. ),
  1656. 'protected' => array(
  1657. 'description' => __( 'Whether the excerpt is protected with a password.' ),
  1658. 'type' => 'boolean',
  1659. 'context' => array( 'view', 'edit', 'embed' ),
  1660. 'readonly' => true,
  1661. ),
  1662. ),
  1663. );
  1664. break;
  1665. case 'thumbnail':
  1666. $schema['properties']['featured_media'] = array(
  1667. 'description' => __( 'The ID of the featured media for the object.' ),
  1668. 'type' => 'integer',
  1669. 'context' => array( 'view', 'edit' ),
  1670. );
  1671. break;
  1672. case 'comments':
  1673. $schema['properties']['comment_status'] = array(
  1674. 'description' => __( 'Whether or not comments are open on the object.' ),
  1675. 'type' => 'string',
  1676. 'enum' => array( 'open', 'closed' ),
  1677. 'context' => array( 'view', 'edit' ),
  1678. );
  1679. $schema['properties']['ping_status'] = array(
  1680. 'description' => __( 'Whether or not the object can be pinged.' ),
  1681. 'type' => 'string',
  1682. 'enum' => array( 'open', 'closed' ),
  1683. 'context' => array( 'view', 'edit' ),
  1684. );
  1685. break;
  1686. case 'page-attributes':
  1687. $schema['properties']['menu_order'] = array(
  1688. 'description' => __( 'The order of the object in relation to other object of its type.' ),
  1689. 'type' => 'integer',
  1690. 'context' => array( 'view', 'edit' ),
  1691. );
  1692. break;
  1693. case 'post-formats':
  1694. // Get the native post formats and remove the array keys.
  1695. $formats = array_values( get_post_format_slugs() );
  1696. $schema['properties']['format'] = array(
  1697. 'description' => __( 'The format for the object.' ),
  1698. 'type' => 'string',
  1699. 'enum' => $formats,
  1700. 'context' => array( 'view', 'edit' ),
  1701. );
  1702. break;
  1703. case 'custom-fields':
  1704. $schema['properties']['meta'] = $this->meta->get_field_schema();
  1705. break;
  1706. }
  1707. }
  1708. if ( 'post' === $this->post_type ) {
  1709. $schema['properties']['sticky'] = array(
  1710. 'description' => __( 'Whether or not the object should be treated as sticky.' ),
  1711. 'type' => 'boolean',
  1712. 'context' => array( 'view', 'edit' ),
  1713. );
  1714. }
  1715. $schema['properties']['template'] = array(
  1716. 'description' => __( 'The theme file to use to display the object.' ),
  1717. 'type' => 'string',
  1718. 'enum' => array_merge( array_keys( wp_get_theme()->get_page_templates( null, $this->post_type ) ), array( '' ) ),
  1719. 'context' => array( 'view', 'edit' ),
  1720. );
  1721. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1722. foreach ( $taxonomies as $taxonomy ) {
  1723. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1724. $schema['properties'][ $base ] = array(
  1725. /* translators: %s: taxonomy name */
  1726. 'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
  1727. 'type' => 'array',
  1728. 'items' => array(
  1729. 'type' => 'integer',
  1730. ),
  1731. 'context' => array( 'view', 'edit' ),
  1732. );
  1733. }
  1734. return $this->add_additional_fields_schema( $schema );
  1735. }
  1736. /**
  1737. * Retrieves the query params for the posts collection.
  1738. *
  1739. * @since 4.7.0
  1740. * @access public
  1741. *
  1742. * @return array Collection parameters.
  1743. */
  1744. public function get_collection_params() {
  1745. $query_params = parent::get_collection_params();
  1746. $query_params['context']['default'] = 'view';
  1747. $query_params['after'] = array(
  1748. 'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
  1749. 'type' => 'string',
  1750. 'format' => 'date-time',
  1751. );
  1752. if ( post_type_supports( $this->post_type, 'author' ) ) {
  1753. $query_params['author'] = array(
  1754. 'description' => __( 'Limit result set to posts assigned to specific authors.' ),
  1755. 'type' => 'array',
  1756. 'items' => array(
  1757. 'type' => 'integer',
  1758. ),
  1759. 'default' => array(),
  1760. );
  1761. $query_params['author_exclude'] = array(
  1762. 'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
  1763. 'type' => 'array',
  1764. 'items' => array(
  1765. 'type' => 'integer',
  1766. ),
  1767. 'default' => array(),
  1768. );
  1769. }
  1770. $query_params['before'] = array(
  1771. 'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
  1772. 'type' => 'string',
  1773. 'format' => 'date-time',
  1774. );
  1775. $query_params['exclude'] = array(
  1776. 'description' => __( 'Ensure result set excludes specific IDs.' ),
  1777. 'type' => 'array',
  1778. 'items' => array(
  1779. 'type' => 'integer',
  1780. ),
  1781. 'default' => array(),
  1782. );
  1783. $query_params['include'] = array(
  1784. 'description' => __( 'Limit result set to specific IDs.' ),
  1785. 'type' => 'array',
  1786. 'items' => array(
  1787. 'type' => 'integer',
  1788. ),
  1789. 'default' => array(),
  1790. );
  1791. if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
  1792. $query_params['menu_order'] = array(
  1793. 'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
  1794. 'type' => 'integer',
  1795. );
  1796. }
  1797. $query_params['offset'] = array(
  1798. 'description' => __( 'Offset the result set by a specific number of items.' ),
  1799. 'type' => 'integer',
  1800. );
  1801. $query_params['order'] = array(
  1802. 'description' => __( 'Order sort attribute ascending or descending.' ),
  1803. 'type' => 'string',
  1804. 'default' => 'desc',
  1805. 'enum' => array( 'asc', 'desc' ),
  1806. );
  1807. $query_params['orderby'] = array(
  1808. 'description' => __( 'Sort collection by object attribute.' ),
  1809. 'type' => 'string',
  1810. 'default' => 'date',
  1811. 'enum' => array(
  1812. 'date',
  1813. 'relevance',
  1814. 'id',
  1815. 'include',
  1816. 'title',
  1817. 'slug',
  1818. ),
  1819. );
  1820. if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
  1821. $query_params['orderby']['enum'][] = 'menu_order';
  1822. }
  1823. $post_type = get_post_type_object( $this->post_type );
  1824. if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
  1825. $query_params['parent'] = array(
  1826. 'description' => __( 'Limit result set to those of particular parent IDs.' ),
  1827. 'type' => 'array',
  1828. 'items' => array(
  1829. 'type' => 'integer',
  1830. ),
  1831. 'default' => array(),
  1832. );
  1833. $query_params['parent_exclude'] = array(
  1834. 'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
  1835. 'type' => 'array',
  1836. 'items' => array(
  1837. 'type' => 'integer',
  1838. ),
  1839. 'default' => array(),
  1840. );
  1841. }
  1842. $query_params['slug'] = array(
  1843. 'description' => __( 'Limit result set to posts with one or more specific slugs.' ),
  1844. 'type' => 'array',
  1845. 'items' => array(
  1846. 'type' => 'string',
  1847. ),
  1848. 'sanitize_callback' => 'wp_parse_slug_list',
  1849. );
  1850. $query_params['status'] = array(
  1851. 'default' => 'publish',
  1852. 'description' => __( 'Limit result set to posts assigned one or more statuses.' ),
  1853. 'type' => 'array',
  1854. 'items' => array(
  1855. 'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
  1856. 'type' => 'string',
  1857. ),
  1858. 'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
  1859. );
  1860. $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
  1861. foreach ( $taxonomies as $taxonomy ) {
  1862. $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
  1863. $query_params[ $base ] = array(
  1864. /* translators: %s: taxonomy name */
  1865. 'description' => sprintf( __( 'Limit result set to all items that have the specified term assigned in the %s taxonomy.' ), $base ),
  1866. 'type' => 'array',
  1867. 'items' => array(
  1868. 'type' => 'integer',
  1869. ),
  1870. 'default' => array(),
  1871. );
  1872. $query_params[ $base . '_exclude' ] = array(
  1873. /* translators: %s: taxonomy name */
  1874. 'description' => sprintf( __( 'Limit result set to all items except those that have the specified term assigned in the %s taxonomy.' ), $base ),
  1875. 'type' => 'array',
  1876. 'items' => array(
  1877. 'type' => 'integer',
  1878. ),
  1879. 'default' => array(),
  1880. );
  1881. }
  1882. if ( 'post' === $this->post_type ) {
  1883. $query_params['sticky'] = array(
  1884. 'description' => __( 'Limit result set to items that are sticky.' ),
  1885. 'type' => 'boolean',
  1886. );
  1887. }
  1888. /**
  1889. * Filter collection parameters for the posts controller.
  1890. *
  1891. * The dynamic part of the filter `$this->post_type` refers to the post
  1892. * type slug for the controller.
  1893. *
  1894. * This filter registers the collection parameter, but does not map the
  1895. * collection parameter to an internal WP_Query parameter. Use the
  1896. * `rest_{$this->post_type}_query` filter to set WP_Query parameters.
  1897. *
  1898. * @since 4.7.0
  1899. *
  1900. * @param array $query_params JSON Schema-formatted collection parameters.
  1901. * @param WP_Post_Type $post_type Post type object.
  1902. */
  1903. return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
  1904. }
  1905. /**
  1906. * Sanitizes and validates the list of post statuses, including whether the
  1907. * user can query private statuses.
  1908. *
  1909. * @since 4.7.0
  1910. * @access public
  1911. *
  1912. * @param string|array $statuses One or more post statuses.
  1913. * @param WP_REST_Request $request Full details about the request.
  1914. * @param string $parameter Additional parameter to pass to validation.
  1915. * @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
  1916. */
  1917. public function sanitize_post_statuses( $statuses, $request, $parameter ) {
  1918. $statuses = wp_parse_slug_list( $statuses );
  1919. // The default status is different in WP_REST_Attachments_Controller
  1920. $attributes = $request->get_attributes();
  1921. $default_status = $attributes['args']['status']['default'];
  1922. foreach ( $statuses as $status ) {
  1923. if ( $status === $default_status ) {
  1924. continue;
  1925. }
  1926. $post_type_obj = get_post_type_object( $this->post_type );
  1927. if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
  1928. $result = rest_validate_request_arg( $status, $request, $parameter );
  1929. if ( is_wp_error( $result ) ) {
  1930. return $result;
  1931. }
  1932. } else {
  1933. return new WP_Error( 'rest_forbidden_status', __( 'Status is forbidden.' ), array( 'status' => rest_authorization_required_code() ) );
  1934. }
  1935. }
  1936. return $statuses;
  1937. }
  1938. }