[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-terms-controller.php (source)

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7