class-wp-rest-terms-controller.php 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. <?php
  2. /**
  3. * REST API: WP_REST_Terms_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core class used to managed terms associated with a taxonomy via the REST API.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see WP_REST_Controller
  15. */
  16. class WP_REST_Terms_Controller extends WP_REST_Controller {
  17. /**
  18. * Taxonomy key.
  19. *
  20. * @since 4.7.0
  21. * @var string
  22. */
  23. protected $taxonomy;
  24. /**
  25. * Instance of a term meta fields object.
  26. *
  27. * @since 4.7.0
  28. * @var WP_REST_Term_Meta_Fields
  29. */
  30. protected $meta;
  31. /**
  32. * Column to have the terms be sorted by.
  33. *
  34. * @since 4.7.0
  35. * @var string
  36. */
  37. protected $sort_column;
  38. /**
  39. * Number of terms that were found.
  40. *
  41. * @since 4.7.0
  42. * @var int
  43. */
  44. protected $total_terms;
  45. /**
  46. * Whether the controller supports batching.
  47. *
  48. * @since 5.9.0
  49. * @var array
  50. */
  51. protected $allow_batch = array( 'v1' => true );
  52. /**
  53. * Constructor.
  54. *
  55. * @since 4.7.0
  56. *
  57. * @param string $taxonomy Taxonomy key.
  58. */
  59. public function __construct( $taxonomy ) {
  60. $this->taxonomy = $taxonomy;
  61. $tax_obj = get_taxonomy( $taxonomy );
  62. $this->rest_base = ! empty( $tax_obj->rest_base ) ? $tax_obj->rest_base : $tax_obj->name;
  63. $this->namespace = ! empty( $tax_obj->rest_namespace ) ? $tax_obj->rest_namespace : 'wp/v2';
  64. $this->meta = new WP_REST_Term_Meta_Fields( $taxonomy );
  65. }
  66. /**
  67. * Registers the routes for terms.
  68. *
  69. * @since 4.7.0
  70. *
  71. * @see register_rest_route()
  72. */
  73. public function register_routes() {
  74. register_rest_route(
  75. $this->namespace,
  76. '/' . $this->rest_base,
  77. array(
  78. array(
  79. 'methods' => WP_REST_Server::READABLE,
  80. 'callback' => array( $this, 'get_items' ),
  81. 'permission_callback' => array( $this, 'get_items_permissions_check' ),
  82. 'args' => $this->get_collection_params(),
  83. ),
  84. array(
  85. 'methods' => WP_REST_Server::CREATABLE,
  86. 'callback' => array( $this, 'create_item' ),
  87. 'permission_callback' => array( $this, 'create_item_permissions_check' ),
  88. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
  89. ),
  90. 'allow_batch' => $this->allow_batch,
  91. 'schema' => array( $this, 'get_public_item_schema' ),
  92. )
  93. );
  94. register_rest_route(
  95. $this->namespace,
  96. '/' . $this->rest_base . '/(?P<id>[\d]+)',
  97. array(
  98. 'args' => array(
  99. 'id' => array(
  100. 'description' => __( 'Unique identifier for the term.' ),
  101. 'type' => 'integer',
  102. ),
  103. ),
  104. array(
  105. 'methods' => WP_REST_Server::READABLE,
  106. 'callback' => array( $this, 'get_item' ),
  107. 'permission_callback' => array( $this, 'get_item_permissions_check' ),
  108. 'args' => array(
  109. 'context' => $this->get_context_param( array( 'default' => 'view' ) ),
  110. ),
  111. ),
  112. array(
  113. 'methods' => WP_REST_Server::EDITABLE,
  114. 'callback' => array( $this, 'update_item' ),
  115. 'permission_callback' => array( $this, 'update_item_permissions_check' ),
  116. 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
  117. ),
  118. array(
  119. 'methods' => WP_REST_Server::DELETABLE,
  120. 'callback' => array( $this, 'delete_item' ),
  121. 'permission_callback' => array( $this, 'delete_item_permissions_check' ),
  122. 'args' => array(
  123. 'force' => array(
  124. 'type' => 'boolean',
  125. 'default' => false,
  126. 'description' => __( 'Required to be true, as terms do not support trashing.' ),
  127. ),
  128. ),
  129. ),
  130. 'allow_batch' => $this->allow_batch,
  131. 'schema' => array( $this, 'get_public_item_schema' ),
  132. )
  133. );
  134. }
  135. /**
  136. * Checks if the terms for a post can be read.
  137. *
  138. * @since 6.0.3
  139. *
  140. * @param WP_Post $post Post object.
  141. * @param WP_REST_Request $request Full details about the request.
  142. * @return bool Whether the terms for the post can be read.
  143. */
  144. public function check_read_terms_permission_for_post( $post, $request ) {
  145. // If the requested post isn't associated with this taxonomy, deny access.
  146. if ( ! is_object_in_taxonomy( $post->post_type, $this->taxonomy ) ) {
  147. return false;
  148. }
  149. // Grant access if the post is publicly viewable.
  150. if ( is_post_publicly_viewable( $post ) ) {
  151. return true;
  152. }
  153. // Otherwise grant access if the post is readable by the logged in user.
  154. if ( current_user_can( 'read_post', $post->ID ) ) {
  155. return true;
  156. }
  157. // Otherwise, deny access.
  158. return false;
  159. }
  160. /**
  161. * Checks if a request has access to read terms in the specified taxonomy.
  162. *
  163. * @since 4.7.0
  164. *
  165. * @param WP_REST_Request $request Full details about the request.
  166. * @return true|WP_Error True if the request has read access, otherwise false or WP_Error object.
  167. */
  168. public function get_items_permissions_check( $request ) {
  169. $tax_obj = get_taxonomy( $this->taxonomy );
  170. if ( ! $tax_obj || ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
  171. return false;
  172. }
  173. if ( 'edit' === $request['context'] && ! current_user_can( $tax_obj->cap->edit_terms ) ) {
  174. return new WP_Error(
  175. 'rest_forbidden_context',
  176. __( 'Sorry, you are not allowed to edit terms in this taxonomy.' ),
  177. array( 'status' => rest_authorization_required_code() )
  178. );
  179. }
  180. if ( ! empty( $request['post'] ) ) {
  181. $post = get_post( $request['post'] );
  182. if ( ! $post ) {
  183. return new WP_Error(
  184. 'rest_post_invalid_id',
  185. __( 'Invalid post ID.' ),
  186. array(
  187. 'status' => 400,
  188. )
  189. );
  190. }
  191. if ( ! $this->check_read_terms_permission_for_post( $post, $request ) ) {
  192. return new WP_Error(
  193. 'rest_forbidden_context',
  194. __( 'Sorry, you are not allowed to view terms for this post.' ),
  195. array(
  196. 'status' => rest_authorization_required_code(),
  197. )
  198. );
  199. }
  200. }
  201. return true;
  202. }
  203. /**
  204. * Retrieves terms associated with a taxonomy.
  205. *
  206. * @since 4.7.0
  207. *
  208. * @param WP_REST_Request $request Full details about the request.
  209. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  210. */
  211. public function get_items( $request ) {
  212. // Retrieve the list of registered collection query parameters.
  213. $registered = $this->get_collection_params();
  214. /*
  215. * This array defines mappings between public API query parameters whose
  216. * values are accepted as-passed, and their internal WP_Query parameter
  217. * name equivalents (some are the same). Only values which are also
  218. * present in $registered will be set.
  219. */
  220. $parameter_mappings = array(
  221. 'exclude' => 'exclude',
  222. 'include' => 'include',
  223. 'order' => 'order',
  224. 'orderby' => 'orderby',
  225. 'post' => 'post',
  226. 'hide_empty' => 'hide_empty',
  227. 'per_page' => 'number',
  228. 'search' => 'search',
  229. 'slug' => 'slug',
  230. );
  231. $prepared_args = array( 'taxonomy' => $this->taxonomy );
  232. /*
  233. * For each known parameter which is both registered and present in the request,
  234. * set the parameter's value on the query $prepared_args.
  235. */
  236. foreach ( $parameter_mappings as $api_param => $wp_param ) {
  237. if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) {
  238. $prepared_args[ $wp_param ] = $request[ $api_param ];
  239. }
  240. }
  241. if ( isset( $prepared_args['orderby'] ) && isset( $request['orderby'] ) ) {
  242. $orderby_mappings = array(
  243. 'include_slugs' => 'slug__in',
  244. );
  245. if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
  246. $prepared_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
  247. }
  248. }
  249. if ( isset( $registered['offset'] ) && ! empty( $request['offset'] ) ) {
  250. $prepared_args['offset'] = $request['offset'];
  251. } else {
  252. $prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number'];
  253. }
  254. $taxonomy_obj = get_taxonomy( $this->taxonomy );
  255. if ( $taxonomy_obj->hierarchical && isset( $registered['parent'], $request['parent'] ) ) {
  256. if ( 0 === $request['parent'] ) {
  257. // Only query top-level terms.
  258. $prepared_args['parent'] = 0;
  259. } else {
  260. if ( $request['parent'] ) {
  261. $prepared_args['parent'] = $request['parent'];
  262. }
  263. }
  264. }
  265. /**
  266. * Filters get_terms() arguments when querying terms via the REST API.
  267. *
  268. * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
  269. *
  270. * Possible hook names include:
  271. *
  272. * - `rest_category_query`
  273. * - `rest_post_tag_query`
  274. *
  275. * Enables adding extra arguments or setting defaults for a terms
  276. * collection request.
  277. *
  278. * @since 4.7.0
  279. *
  280. * @link https://developer.wordpress.org/reference/functions/get_terms/
  281. *
  282. * @param array $prepared_args Array of arguments for get_terms().
  283. * @param WP_REST_Request $request The REST API request.
  284. */
  285. $prepared_args = apply_filters( "rest_{$this->taxonomy}_query", $prepared_args, $request );
  286. if ( ! empty( $prepared_args['post'] ) ) {
  287. $query_result = wp_get_object_terms( $prepared_args['post'], $this->taxonomy, $prepared_args );
  288. // Used when calling wp_count_terms() below.
  289. $prepared_args['object_ids'] = $prepared_args['post'];
  290. } else {
  291. $query_result = get_terms( $prepared_args );
  292. }
  293. $count_args = $prepared_args;
  294. unset( $count_args['number'], $count_args['offset'] );
  295. $total_terms = wp_count_terms( $count_args );
  296. // wp_count_terms() can return a falsey value when the term has no children.
  297. if ( ! $total_terms ) {
  298. $total_terms = 0;
  299. }
  300. $response = array();
  301. foreach ( $query_result as $term ) {
  302. $data = $this->prepare_item_for_response( $term, $request );
  303. $response[] = $this->prepare_response_for_collection( $data );
  304. }
  305. $response = rest_ensure_response( $response );
  306. // Store pagination values for headers.
  307. $per_page = (int) $prepared_args['number'];
  308. $page = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 );
  309. $response->header( 'X-WP-Total', (int) $total_terms );
  310. $max_pages = ceil( $total_terms / $per_page );
  311. $response->header( 'X-WP-TotalPages', (int) $max_pages );
  312. $request_params = $request->get_query_params();
  313. $collection_url = rest_url( rest_get_route_for_taxonomy_items( $this->taxonomy ) );
  314. $base = add_query_arg( urlencode_deep( $request_params ), $collection_url );
  315. if ( $page > 1 ) {
  316. $prev_page = $page - 1;
  317. if ( $prev_page > $max_pages ) {
  318. $prev_page = $max_pages;
  319. }
  320. $prev_link = add_query_arg( 'page', $prev_page, $base );
  321. $response->link_header( 'prev', $prev_link );
  322. }
  323. if ( $max_pages > $page ) {
  324. $next_page = $page + 1;
  325. $next_link = add_query_arg( 'page', $next_page, $base );
  326. $response->link_header( 'next', $next_link );
  327. }
  328. return $response;
  329. }
  330. /**
  331. * Get the term, if the ID is valid.
  332. *
  333. * @since 4.7.2
  334. *
  335. * @param int $id Supplied ID.
  336. * @return WP_Term|WP_Error Term object if ID is valid, WP_Error otherwise.
  337. */
  338. protected function get_term( $id ) {
  339. $error = new WP_Error(
  340. 'rest_term_invalid',
  341. __( 'Term does not exist.' ),
  342. array( 'status' => 404 )
  343. );
  344. if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
  345. return $error;
  346. }
  347. if ( (int) $id <= 0 ) {
  348. return $error;
  349. }
  350. $term = get_term( (int) $id, $this->taxonomy );
  351. if ( empty( $term ) || $term->taxonomy !== $this->taxonomy ) {
  352. return $error;
  353. }
  354. return $term;
  355. }
  356. /**
  357. * Checks if a request has access to read or edit the specified term.
  358. *
  359. * @since 4.7.0
  360. *
  361. * @param WP_REST_Request $request Full details about the request.
  362. * @return true|WP_Error True if the request has read access for the item, otherwise false or WP_Error object.
  363. */
  364. public function get_item_permissions_check( $request ) {
  365. $term = $this->get_term( $request['id'] );
  366. if ( is_wp_error( $term ) ) {
  367. return $term;
  368. }
  369. if ( 'edit' === $request['context'] && ! current_user_can( 'edit_term', $term->term_id ) ) {
  370. return new WP_Error(
  371. 'rest_forbidden_context',
  372. __( 'Sorry, you are not allowed to edit this term.' ),
  373. array( 'status' => rest_authorization_required_code() )
  374. );
  375. }
  376. return true;
  377. }
  378. /**
  379. * Gets a single term from a taxonomy.
  380. *
  381. * @since 4.7.0
  382. *
  383. * @param WP_REST_Request $request Full details about the request.
  384. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  385. */
  386. public function get_item( $request ) {
  387. $term = $this->get_term( $request['id'] );
  388. if ( is_wp_error( $term ) ) {
  389. return $term;
  390. }
  391. $response = $this->prepare_item_for_response( $term, $request );
  392. return rest_ensure_response( $response );
  393. }
  394. /**
  395. * Checks if a request has access to create a term.
  396. *
  397. * @since 4.7.0
  398. *
  399. * @param WP_REST_Request $request Full details about the request.
  400. * @return true|WP_Error True if the request has access to create items, false or WP_Error object otherwise.
  401. */
  402. public function create_item_permissions_check( $request ) {
  403. if ( ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) {
  404. return false;
  405. }
  406. $taxonomy_obj = get_taxonomy( $this->taxonomy );
  407. if ( ( is_taxonomy_hierarchical( $this->taxonomy )
  408. && ! current_user_can( $taxonomy_obj->cap->edit_terms ) )
  409. || ( ! is_taxonomy_hierarchical( $this->taxonomy )
  410. && ! current_user_can( $taxonomy_obj->cap->assign_terms ) ) ) {
  411. return new WP_Error(
  412. 'rest_cannot_create',
  413. __( 'Sorry, you are not allowed to create terms in this taxonomy.' ),
  414. array( 'status' => rest_authorization_required_code() )
  415. );
  416. }
  417. return true;
  418. }
  419. /**
  420. * Creates a single term in a taxonomy.
  421. *
  422. * @since 4.7.0
  423. *
  424. * @param WP_REST_Request $request Full details about the request.
  425. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  426. */
  427. public function create_item( $request ) {
  428. if ( isset( $request['parent'] ) ) {
  429. if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
  430. return new WP_Error(
  431. 'rest_taxonomy_not_hierarchical',
  432. __( 'Cannot set parent term, taxonomy is not hierarchical.' ),
  433. array( 'status' => 400 )
  434. );
  435. }
  436. $parent = get_term( (int) $request['parent'], $this->taxonomy );
  437. if ( ! $parent ) {
  438. return new WP_Error(
  439. 'rest_term_invalid',
  440. __( 'Parent term does not exist.' ),
  441. array( 'status' => 400 )
  442. );
  443. }
  444. }
  445. $prepared_term = $this->prepare_item_for_database( $request );
  446. $term = wp_insert_term( wp_slash( $prepared_term->name ), $this->taxonomy, wp_slash( (array) $prepared_term ) );
  447. if ( is_wp_error( $term ) ) {
  448. /*
  449. * If we're going to inform the client that the term already exists,
  450. * give them the identifier for future use.
  451. */
  452. $term_id = $term->get_error_data( 'term_exists' );
  453. if ( $term_id ) {
  454. $existing_term = get_term( $term_id, $this->taxonomy );
  455. $term->add_data( $existing_term->term_id, 'term_exists' );
  456. $term->add_data(
  457. array(
  458. 'status' => 400,
  459. 'term_id' => $term_id,
  460. )
  461. );
  462. }
  463. return $term;
  464. }
  465. $term = get_term( $term['term_id'], $this->taxonomy );
  466. /**
  467. * Fires after a single term is created or updated via the REST API.
  468. *
  469. * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
  470. *
  471. * Possible hook names include:
  472. *
  473. * - `rest_insert_category`
  474. * - `rest_insert_post_tag`
  475. *
  476. * @since 4.7.0
  477. *
  478. * @param WP_Term $term Inserted or updated term object.
  479. * @param WP_REST_Request $request Request object.
  480. * @param bool $creating True when creating a term, false when updating.
  481. */
  482. do_action( "rest_insert_{$this->taxonomy}", $term, $request, true );
  483. $schema = $this->get_item_schema();
  484. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  485. $meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
  486. if ( is_wp_error( $meta_update ) ) {
  487. return $meta_update;
  488. }
  489. }
  490. $fields_update = $this->update_additional_fields_for_object( $term, $request );
  491. if ( is_wp_error( $fields_update ) ) {
  492. return $fields_update;
  493. }
  494. $request->set_param( 'context', 'edit' );
  495. /**
  496. * Fires after a single term is completely created or updated via the REST API.
  497. *
  498. * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
  499. *
  500. * Possible hook names include:
  501. *
  502. * - `rest_after_insert_category`
  503. * - `rest_after_insert_post_tag`
  504. *
  505. * @since 5.0.0
  506. *
  507. * @param WP_Term $term Inserted or updated term object.
  508. * @param WP_REST_Request $request Request object.
  509. * @param bool $creating True when creating a term, false when updating.
  510. */
  511. do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, true );
  512. $response = $this->prepare_item_for_response( $term, $request );
  513. $response = rest_ensure_response( $response );
  514. $response->set_status( 201 );
  515. $response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . $term->term_id ) );
  516. return $response;
  517. }
  518. /**
  519. * Checks if a request has access to update the specified term.
  520. *
  521. * @since 4.7.0
  522. *
  523. * @param WP_REST_Request $request Full details about the request.
  524. * @return true|WP_Error True if the request has access to update the item, false or WP_Error object otherwise.
  525. */
  526. public function update_item_permissions_check( $request ) {
  527. $term = $this->get_term( $request['id'] );
  528. if ( is_wp_error( $term ) ) {
  529. return $term;
  530. }
  531. if ( ! current_user_can( 'edit_term', $term->term_id ) ) {
  532. return new WP_Error(
  533. 'rest_cannot_update',
  534. __( 'Sorry, you are not allowed to edit this term.' ),
  535. array( 'status' => rest_authorization_required_code() )
  536. );
  537. }
  538. return true;
  539. }
  540. /**
  541. * Updates a single term from a taxonomy.
  542. *
  543. * @since 4.7.0
  544. *
  545. * @param WP_REST_Request $request Full details about the request.
  546. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  547. */
  548. public function update_item( $request ) {
  549. $term = $this->get_term( $request['id'] );
  550. if ( is_wp_error( $term ) ) {
  551. return $term;
  552. }
  553. if ( isset( $request['parent'] ) ) {
  554. if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) {
  555. return new WP_Error(
  556. 'rest_taxonomy_not_hierarchical',
  557. __( 'Cannot set parent term, taxonomy is not hierarchical.' ),
  558. array( 'status' => 400 )
  559. );
  560. }
  561. $parent = get_term( (int) $request['parent'], $this->taxonomy );
  562. if ( ! $parent ) {
  563. return new WP_Error(
  564. 'rest_term_invalid',
  565. __( 'Parent term does not exist.' ),
  566. array( 'status' => 400 )
  567. );
  568. }
  569. }
  570. $prepared_term = $this->prepare_item_for_database( $request );
  571. // Only update the term if we have something to update.
  572. if ( ! empty( $prepared_term ) ) {
  573. $update = wp_update_term( $term->term_id, $term->taxonomy, wp_slash( (array) $prepared_term ) );
  574. if ( is_wp_error( $update ) ) {
  575. return $update;
  576. }
  577. }
  578. $term = get_term( $term->term_id, $this->taxonomy );
  579. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
  580. do_action( "rest_insert_{$this->taxonomy}", $term, $request, false );
  581. $schema = $this->get_item_schema();
  582. if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
  583. $meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
  584. if ( is_wp_error( $meta_update ) ) {
  585. return $meta_update;
  586. }
  587. }
  588. $fields_update = $this->update_additional_fields_for_object( $term, $request );
  589. if ( is_wp_error( $fields_update ) ) {
  590. return $fields_update;
  591. }
  592. $request->set_param( 'context', 'edit' );
  593. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
  594. do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, false );
  595. $response = $this->prepare_item_for_response( $term, $request );
  596. return rest_ensure_response( $response );
  597. }
  598. /**
  599. * Checks if a request has access to delete the specified term.
  600. *
  601. * @since 4.7.0
  602. *
  603. * @param WP_REST_Request $request Full details about the request.
  604. * @return true|WP_Error True if the request has access to delete the item, otherwise false or WP_Error object.
  605. */
  606. public function delete_item_permissions_check( $request ) {
  607. $term = $this->get_term( $request['id'] );
  608. if ( is_wp_error( $term ) ) {
  609. return $term;
  610. }
  611. if ( ! current_user_can( 'delete_term', $term->term_id ) ) {
  612. return new WP_Error(
  613. 'rest_cannot_delete',
  614. __( 'Sorry, you are not allowed to delete this term.' ),
  615. array( 'status' => rest_authorization_required_code() )
  616. );
  617. }
  618. return true;
  619. }
  620. /**
  621. * Deletes a single term from a taxonomy.
  622. *
  623. * @since 4.7.0
  624. *
  625. * @param WP_REST_Request $request Full details about the request.
  626. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  627. */
  628. public function delete_item( $request ) {
  629. $term = $this->get_term( $request['id'] );
  630. if ( is_wp_error( $term ) ) {
  631. return $term;
  632. }
  633. $force = isset( $request['force'] ) ? (bool) $request['force'] : false;
  634. // We don't support trashing for terms.
  635. if ( ! $force ) {
  636. return new WP_Error(
  637. 'rest_trash_not_supported',
  638. /* translators: %s: force=true */
  639. sprintf( __( "Terms do not support trashing. Set '%s' to delete." ), 'force=true' ),
  640. array( 'status' => 501 )
  641. );
  642. }
  643. $request->set_param( 'context', 'view' );
  644. $previous = $this->prepare_item_for_response( $term, $request );
  645. $retval = wp_delete_term( $term->term_id, $term->taxonomy );
  646. if ( ! $retval ) {
  647. return new WP_Error(
  648. 'rest_cannot_delete',
  649. __( 'The term cannot be deleted.' ),
  650. array( 'status' => 500 )
  651. );
  652. }
  653. $response = new WP_REST_Response();
  654. $response->set_data(
  655. array(
  656. 'deleted' => true,
  657. 'previous' => $previous->get_data(),
  658. )
  659. );
  660. /**
  661. * Fires after a single term is deleted via the REST API.
  662. *
  663. * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
  664. *
  665. * Possible hook names include:
  666. *
  667. * - `rest_delete_category`
  668. * - `rest_delete_post_tag`
  669. *
  670. * @since 4.7.0
  671. *
  672. * @param WP_Term $term The deleted term.
  673. * @param WP_REST_Response $response The response data.
  674. * @param WP_REST_Request $request The request sent to the API.
  675. */
  676. do_action( "rest_delete_{$this->taxonomy}", $term, $response, $request );
  677. return $response;
  678. }
  679. /**
  680. * Prepares a single term for create or update.
  681. *
  682. * @since 4.7.0
  683. *
  684. * @param WP_REST_Request $request Request object.
  685. * @return object Term object.
  686. */
  687. public function prepare_item_for_database( $request ) {
  688. $prepared_term = new stdClass;
  689. $schema = $this->get_item_schema();
  690. if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
  691. $prepared_term->name = $request['name'];
  692. }
  693. if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
  694. $prepared_term->slug = $request['slug'];
  695. }
  696. if ( isset( $request['taxonomy'] ) && ! empty( $schema['properties']['taxonomy'] ) ) {
  697. $prepared_term->taxonomy = $request['taxonomy'];
  698. }
  699. if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
  700. $prepared_term->description = $request['description'];
  701. }
  702. if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
  703. $parent_term_id = 0;
  704. $requested_parent = (int) $request['parent'];
  705. if ( $requested_parent ) {
  706. $parent_term = get_term( $requested_parent, $this->taxonomy );
  707. if ( $parent_term instanceof WP_Term ) {
  708. $parent_term_id = $parent_term->term_id;
  709. }
  710. }
  711. $prepared_term->parent = $parent_term_id;
  712. }
  713. /**
  714. * Filters term data before inserting term via the REST API.
  715. *
  716. * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
  717. *
  718. * Possible hook names include:
  719. *
  720. * - `rest_pre_insert_category`
  721. * - `rest_pre_insert_post_tag`
  722. *
  723. * @since 4.7.0
  724. *
  725. * @param object $prepared_term Term object.
  726. * @param WP_REST_Request $request Request object.
  727. */
  728. return apply_filters( "rest_pre_insert_{$this->taxonomy}", $prepared_term, $request );
  729. }
  730. /**
  731. * Prepares a single term output for response.
  732. *
  733. * @since 4.7.0
  734. *
  735. * @param WP_Term $item Term object.
  736. * @param WP_REST_Request $request Request object.
  737. * @return WP_REST_Response Response object.
  738. */
  739. public function prepare_item_for_response( $item, $request ) {
  740. $fields = $this->get_fields_for_response( $request );
  741. $data = array();
  742. if ( in_array( 'id', $fields, true ) ) {
  743. $data['id'] = (int) $item->term_id;
  744. }
  745. if ( in_array( 'count', $fields, true ) ) {
  746. $data['count'] = (int) $item->count;
  747. }
  748. if ( in_array( 'description', $fields, true ) ) {
  749. $data['description'] = $item->description;
  750. }
  751. if ( in_array( 'link', $fields, true ) ) {
  752. $data['link'] = get_term_link( $item );
  753. }
  754. if ( in_array( 'name', $fields, true ) ) {
  755. $data['name'] = $item->name;
  756. }
  757. if ( in_array( 'slug', $fields, true ) ) {
  758. $data['slug'] = $item->slug;
  759. }
  760. if ( in_array( 'taxonomy', $fields, true ) ) {
  761. $data['taxonomy'] = $item->taxonomy;
  762. }
  763. if ( in_array( 'parent', $fields, true ) ) {
  764. $data['parent'] = (int) $item->parent;
  765. }
  766. if ( in_array( 'meta', $fields, true ) ) {
  767. $data['meta'] = $this->meta->get_value( $item->term_id, $request );
  768. }
  769. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  770. $data = $this->add_additional_fields_to_object( $data, $request );
  771. $data = $this->filter_response_by_context( $data, $context );
  772. $response = rest_ensure_response( $data );
  773. if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
  774. $response->add_links( $this->prepare_links( $item ) );
  775. }
  776. /**
  777. * Filters the term data for a REST API response.
  778. *
  779. * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
  780. *
  781. * Possible hook names include:
  782. *
  783. * - `rest_prepare_category`
  784. * - `rest_prepare_post_tag`
  785. *
  786. * Allows modification of the term data right before it is returned.
  787. *
  788. * @since 4.7.0
  789. *
  790. * @param WP_REST_Response $response The response object.
  791. * @param WP_Term $item The original term object.
  792. * @param WP_REST_Request $request Request used to generate the response.
  793. */
  794. return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $item, $request );
  795. }
  796. /**
  797. * Prepares links for the request.
  798. *
  799. * @since 4.7.0
  800. *
  801. * @param WP_Term $term Term object.
  802. * @return array Links for the given term.
  803. */
  804. protected function prepare_links( $term ) {
  805. $links = array(
  806. 'self' => array(
  807. 'href' => rest_url( rest_get_route_for_term( $term ) ),
  808. ),
  809. 'collection' => array(
  810. 'href' => rest_url( rest_get_route_for_taxonomy_items( $this->taxonomy ) ),
  811. ),
  812. 'about' => array(
  813. 'href' => rest_url( sprintf( 'wp/v2/taxonomies/%s', $this->taxonomy ) ),
  814. ),
  815. );
  816. if ( $term->parent ) {
  817. $parent_term = get_term( (int) $term->parent, $term->taxonomy );
  818. if ( $parent_term ) {
  819. $links['up'] = array(
  820. 'href' => rest_url( rest_get_route_for_term( $parent_term ) ),
  821. 'embeddable' => true,
  822. );
  823. }
  824. }
  825. $taxonomy_obj = get_taxonomy( $term->taxonomy );
  826. if ( empty( $taxonomy_obj->object_type ) ) {
  827. return $links;
  828. }
  829. $post_type_links = array();
  830. foreach ( $taxonomy_obj->object_type as $type ) {
  831. $rest_path = rest_get_route_for_post_type_items( $type );
  832. if ( empty( $rest_path ) ) {
  833. continue;
  834. }
  835. $post_type_links[] = array(
  836. 'href' => add_query_arg( $this->rest_base, $term->term_id, rest_url( $rest_path ) ),
  837. );
  838. }
  839. if ( ! empty( $post_type_links ) ) {
  840. $links['https://api.w.org/post_type'] = $post_type_links;
  841. }
  842. return $links;
  843. }
  844. /**
  845. * Retrieves the term's schema, conforming to JSON Schema.
  846. *
  847. * @since 4.7.0
  848. *
  849. * @return array Item schema data.
  850. */
  851. public function get_item_schema() {
  852. if ( $this->schema ) {
  853. return $this->add_additional_fields_schema( $this->schema );
  854. }
  855. $schema = array(
  856. '$schema' => 'http://json-schema.org/draft-04/schema#',
  857. 'title' => 'post_tag' === $this->taxonomy ? 'tag' : $this->taxonomy,
  858. 'type' => 'object',
  859. 'properties' => array(
  860. 'id' => array(
  861. 'description' => __( 'Unique identifier for the term.' ),
  862. 'type' => 'integer',
  863. 'context' => array( 'view', 'embed', 'edit' ),
  864. 'readonly' => true,
  865. ),
  866. 'count' => array(
  867. 'description' => __( 'Number of published posts for the term.' ),
  868. 'type' => 'integer',
  869. 'context' => array( 'view', 'edit' ),
  870. 'readonly' => true,
  871. ),
  872. 'description' => array(
  873. 'description' => __( 'HTML description of the term.' ),
  874. 'type' => 'string',
  875. 'context' => array( 'view', 'edit' ),
  876. ),
  877. 'link' => array(
  878. 'description' => __( 'URL of the term.' ),
  879. 'type' => 'string',
  880. 'format' => 'uri',
  881. 'context' => array( 'view', 'embed', 'edit' ),
  882. 'readonly' => true,
  883. ),
  884. 'name' => array(
  885. 'description' => __( 'HTML title for the term.' ),
  886. 'type' => 'string',
  887. 'context' => array( 'view', 'embed', 'edit' ),
  888. 'arg_options' => array(
  889. 'sanitize_callback' => 'sanitize_text_field',
  890. ),
  891. 'required' => true,
  892. ),
  893. 'slug' => array(
  894. 'description' => __( 'An alphanumeric identifier for the term unique to its type.' ),
  895. 'type' => 'string',
  896. 'context' => array( 'view', 'embed', 'edit' ),
  897. 'arg_options' => array(
  898. 'sanitize_callback' => array( $this, 'sanitize_slug' ),
  899. ),
  900. ),
  901. 'taxonomy' => array(
  902. 'description' => __( 'Type attribution for the term.' ),
  903. 'type' => 'string',
  904. 'enum' => array( $this->taxonomy ),
  905. 'context' => array( 'view', 'embed', 'edit' ),
  906. 'readonly' => true,
  907. ),
  908. ),
  909. );
  910. $taxonomy = get_taxonomy( $this->taxonomy );
  911. if ( $taxonomy->hierarchical ) {
  912. $schema['properties']['parent'] = array(
  913. 'description' => __( 'The parent term ID.' ),
  914. 'type' => 'integer',
  915. 'context' => array( 'view', 'edit' ),
  916. );
  917. }
  918. $schema['properties']['meta'] = $this->meta->get_field_schema();
  919. $this->schema = $schema;
  920. return $this->add_additional_fields_schema( $this->schema );
  921. }
  922. /**
  923. * Retrieves the query params for collections.
  924. *
  925. * @since 4.7.0
  926. *
  927. * @return array Collection parameters.
  928. */
  929. public function get_collection_params() {
  930. $query_params = parent::get_collection_params();
  931. $taxonomy = get_taxonomy( $this->taxonomy );
  932. $query_params['context']['default'] = 'view';
  933. $query_params['exclude'] = array(
  934. 'description' => __( 'Ensure result set excludes specific IDs.' ),
  935. 'type' => 'array',
  936. 'items' => array(
  937. 'type' => 'integer',
  938. ),
  939. 'default' => array(),
  940. );
  941. $query_params['include'] = array(
  942. 'description' => __( 'Limit result set to specific IDs.' ),
  943. 'type' => 'array',
  944. 'items' => array(
  945. 'type' => 'integer',
  946. ),
  947. 'default' => array(),
  948. );
  949. if ( ! $taxonomy->hierarchical ) {
  950. $query_params['offset'] = array(
  951. 'description' => __( 'Offset the result set by a specific number of items.' ),
  952. 'type' => 'integer',
  953. );
  954. }
  955. $query_params['order'] = array(
  956. 'description' => __( 'Order sort attribute ascending or descending.' ),
  957. 'type' => 'string',
  958. 'default' => 'asc',
  959. 'enum' => array(
  960. 'asc',
  961. 'desc',
  962. ),
  963. );
  964. $query_params['orderby'] = array(
  965. 'description' => __( 'Sort collection by term attribute.' ),
  966. 'type' => 'string',
  967. 'default' => 'name',
  968. 'enum' => array(
  969. 'id',
  970. 'include',
  971. 'name',
  972. 'slug',
  973. 'include_slugs',
  974. 'term_group',
  975. 'description',
  976. 'count',
  977. ),
  978. );
  979. $query_params['hide_empty'] = array(
  980. 'description' => __( 'Whether to hide terms not assigned to any posts.' ),
  981. 'type' => 'boolean',
  982. 'default' => false,
  983. );
  984. if ( $taxonomy->hierarchical ) {
  985. $query_params['parent'] = array(
  986. 'description' => __( 'Limit result set to terms assigned to a specific parent.' ),
  987. 'type' => 'integer',
  988. );
  989. }
  990. $query_params['post'] = array(
  991. 'description' => __( 'Limit result set to terms assigned to a specific post.' ),
  992. 'type' => 'integer',
  993. 'default' => null,
  994. );
  995. $query_params['slug'] = array(
  996. 'description' => __( 'Limit result set to terms with one or more specific slugs.' ),
  997. 'type' => 'array',
  998. 'items' => array(
  999. 'type' => 'string',
  1000. ),
  1001. );
  1002. /**
  1003. * Filters collection parameters for the terms controller.
  1004. *
  1005. * The dynamic part of the filter `$this->taxonomy` refers to the taxonomy
  1006. * slug for the controller.
  1007. *
  1008. * This filter registers the collection parameter, but does not map the
  1009. * collection parameter to an internal WP_Term_Query parameter. Use the
  1010. * `rest_{$this->taxonomy}_query` filter to set WP_Term_Query parameters.
  1011. *
  1012. * @since 4.7.0
  1013. *
  1014. * @param array $query_params JSON Schema-formatted collection parameters.
  1015. * @param WP_Taxonomy $taxonomy Taxonomy object.
  1016. */
  1017. return apply_filters( "rest_{$this->taxonomy}_collection_params", $query_params, $taxonomy );
  1018. }
  1019. /**
  1020. * Checks that the taxonomy is valid.
  1021. *
  1022. * @since 4.7.0
  1023. *
  1024. * @param string $taxonomy Taxonomy to check.
  1025. * @return bool Whether the taxonomy is allowed for REST management.
  1026. */
  1027. protected function check_is_taxonomy_allowed( $taxonomy ) {
  1028. $taxonomy_obj = get_taxonomy( $taxonomy );
  1029. if ( $taxonomy_obj && ! empty( $taxonomy_obj->show_in_rest ) ) {
  1030. return true;
  1031. }
  1032. return false;
  1033. }
  1034. }