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

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