class-wp-rest-posts-controller.php 77 KB

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