You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1020 rivejä
30 KiB

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