暫無描述

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

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