[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Sat Nov 23 08:20:01 2024 Cross-referenced by PHPXref