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

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