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

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