暫無描述

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

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