[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> taxonomy.php (source)

   1  <?php
   2  /**
   3   * Core Taxonomy API
   4   *
   5   * @package WordPress
   6   * @subpackage Taxonomy
   7   */
   8  
   9  //
  10  // Taxonomy registration.
  11  //
  12  
  13  /**
  14   * Creates the initial taxonomies.
  15   *
  16   * This function fires twice: in wp-settings.php before plugins are loaded (for
  17   * backward compatibility reasons), and again on the {@see 'init'} action. We must
  18   * avoid registering rewrite rules before the {@see 'init'} action.
  19   *
  20   * @since 2.8.0
  21   *
  22   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
  23   */
  24  function create_initial_taxonomies() {
  25      global $wp_rewrite;
  26  
  27      if ( ! did_action( 'init' ) ) {
  28          $rewrite = array(
  29              'category'    => false,
  30              'post_tag'    => false,
  31              'post_format' => false,
  32          );
  33      } else {
  34  
  35          /**
  36           * Filters the post formats rewrite base.
  37           *
  38           * @since 3.1.0
  39           *
  40           * @param string $context Context of the rewrite base. Default 'type'.
  41           */
  42          $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' );
  43          $rewrite          = array(
  44              'category'    => array(
  45                  'hierarchical' => true,
  46                  'slug'         => get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category',
  47                  'with_front'   => ! get_option( 'category_base' ) || $wp_rewrite->using_index_permalinks(),
  48                  'ep_mask'      => EP_CATEGORIES,
  49              ),
  50              'post_tag'    => array(
  51                  'hierarchical' => false,
  52                  'slug'         => get_option( 'tag_base' ) ? get_option( 'tag_base' ) : 'tag',
  53                  'with_front'   => ! get_option( 'tag_base' ) || $wp_rewrite->using_index_permalinks(),
  54                  'ep_mask'      => EP_TAGS,
  55              ),
  56              'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false,
  57          );
  58      }
  59  
  60      register_taxonomy(
  61          'category',
  62          'post',
  63          array(
  64              'hierarchical'          => true,
  65              'query_var'             => 'category_name',
  66              'rewrite'               => $rewrite['category'],
  67              'public'                => true,
  68              'show_ui'               => true,
  69              'show_admin_column'     => true,
  70              '_builtin'              => true,
  71              'capabilities'          => array(
  72                  'manage_terms' => 'manage_categories',
  73                  'edit_terms'   => 'edit_categories',
  74                  'delete_terms' => 'delete_categories',
  75                  'assign_terms' => 'assign_categories',
  76              ),
  77              'show_in_rest'          => true,
  78              'rest_base'             => 'categories',
  79              'rest_controller_class' => 'WP_REST_Terms_Controller',
  80          )
  81      );
  82  
  83      register_taxonomy(
  84          'post_tag',
  85          'post',
  86          array(
  87              'hierarchical'          => false,
  88              'query_var'             => 'tag',
  89              'rewrite'               => $rewrite['post_tag'],
  90              'public'                => true,
  91              'show_ui'               => true,
  92              'show_admin_column'     => true,
  93              '_builtin'              => true,
  94              'capabilities'          => array(
  95                  'manage_terms' => 'manage_post_tags',
  96                  'edit_terms'   => 'edit_post_tags',
  97                  'delete_terms' => 'delete_post_tags',
  98                  'assign_terms' => 'assign_post_tags',
  99              ),
 100              'show_in_rest'          => true,
 101              'rest_base'             => 'tags',
 102              'rest_controller_class' => 'WP_REST_Terms_Controller',
 103          )
 104      );
 105  
 106      register_taxonomy(
 107          'nav_menu',
 108          'nav_menu_item',
 109          array(
 110              'public'            => false,
 111              'hierarchical'      => false,
 112              'labels'            => array(
 113                  'name'          => __( 'Navigation Menus' ),
 114                  'singular_name' => __( 'Navigation Menu' ),
 115              ),
 116              'query_var'         => false,
 117              'rewrite'           => false,
 118              'show_ui'           => false,
 119              '_builtin'          => true,
 120              'show_in_nav_menus' => false,
 121          )
 122      );
 123  
 124      register_taxonomy(
 125          'link_category',
 126          'link',
 127          array(
 128              'hierarchical' => false,
 129              'labels'       => array(
 130                  'name'                       => __( 'Link Categories' ),
 131                  'singular_name'              => __( 'Link Category' ),
 132                  'search_items'               => __( 'Search Link Categories' ),
 133                  'popular_items'              => null,
 134                  'all_items'                  => __( 'All Link Categories' ),
 135                  'edit_item'                  => __( 'Edit Link Category' ),
 136                  'update_item'                => __( 'Update Link Category' ),
 137                  'add_new_item'               => __( 'Add New Link Category' ),
 138                  'new_item_name'              => __( 'New Link Category Name' ),
 139                  'separate_items_with_commas' => null,
 140                  'add_or_remove_items'        => null,
 141                  'choose_from_most_used'      => null,
 142                  'back_to_items'              => __( '&larr; Go to Link Categories' ),
 143              ),
 144              'capabilities' => array(
 145                  'manage_terms' => 'manage_links',
 146                  'edit_terms'   => 'manage_links',
 147                  'delete_terms' => 'manage_links',
 148                  'assign_terms' => 'manage_links',
 149              ),
 150              'query_var'    => false,
 151              'rewrite'      => false,
 152              'public'       => false,
 153              'show_ui'      => true,
 154              '_builtin'     => true,
 155          )
 156      );
 157  
 158      register_taxonomy(
 159          'post_format',
 160          'post',
 161          array(
 162              'public'            => true,
 163              'hierarchical'      => false,
 164              'labels'            => array(
 165                  'name'          => _x( 'Formats', 'post format' ),
 166                  'singular_name' => _x( 'Format', 'post format' ),
 167              ),
 168              'query_var'         => true,
 169              'rewrite'           => $rewrite['post_format'],
 170              'show_ui'           => false,
 171              '_builtin'          => true,
 172              'show_in_nav_menus' => current_theme_supports( 'post-formats' ),
 173          )
 174      );
 175  }
 176  
 177  /**
 178   * Retrieves a list of registered taxonomy names or objects.
 179   *
 180   * @since 3.0.0
 181   *
 182   * @global array $wp_taxonomies The registered taxonomies.
 183   *
 184   * @param array  $args     Optional. An array of `key => value` arguments to match against the taxonomy objects.
 185   *                         Default empty array.
 186   * @param string $output   Optional. The type of output to return in the array. Accepts either taxonomy 'names'
 187   *                         or 'objects'. Default 'names'.
 188   * @param string $operator Optional. The logical operation to perform. Accepts 'and' or 'or'. 'or' means only
 189   *                         one element from the array needs to match; 'and' means all elements must match.
 190   *                         Default 'and'.
 191   * @return string[]|WP_Taxonomy[] An array of taxonomy names or objects.
 192   */
 193  function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) {
 194      global $wp_taxonomies;
 195  
 196      $field = ( 'names' === $output ) ? 'name' : false;
 197  
 198      return wp_filter_object_list( $wp_taxonomies, $args, $operator, $field );
 199  }
 200  
 201  /**
 202   * Return the names or objects of the taxonomies which are registered for the requested object or object type, such as
 203   * a post object or post type name.
 204   *
 205   * Example:
 206   *
 207   *     $taxonomies = get_object_taxonomies( 'post' );
 208   *
 209   * This results in:
 210   *
 211   *     Array( 'category', 'post_tag' )
 212   *
 213   * @since 2.3.0
 214   *
 215   * @global array $wp_taxonomies The registered taxonomies.
 216   *
 217   * @param string|string[]|WP_Post $object Name of the type of taxonomy object, or an object (row from posts)
 218   * @param string                  $output Optional. The type of output to return in the array. Accepts either
 219   *                                        'names' or 'objects'. Default 'names'.
 220   * @return string[]|WP_Taxonomy[] The names or objects of all taxonomies of `$object_type`.
 221   */
 222  function get_object_taxonomies( $object, $output = 'names' ) {
 223      global $wp_taxonomies;
 224  
 225      if ( is_object( $object ) ) {
 226          if ( 'attachment' === $object->post_type ) {
 227              return get_attachment_taxonomies( $object, $output );
 228          }
 229          $object = $object->post_type;
 230      }
 231  
 232      $object = (array) $object;
 233  
 234      $taxonomies = array();
 235      foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) {
 236          if ( array_intersect( $object, (array) $tax_obj->object_type ) ) {
 237              if ( 'names' === $output ) {
 238                  $taxonomies[] = $tax_name;
 239              } else {
 240                  $taxonomies[ $tax_name ] = $tax_obj;
 241              }
 242          }
 243      }
 244  
 245      return $taxonomies;
 246  }
 247  
 248  /**
 249   * Retrieves the taxonomy object of $taxonomy.
 250   *
 251   * The get_taxonomy function will first check that the parameter string given
 252   * is a taxonomy object and if it is, it will return it.
 253   *
 254   * @since 2.3.0
 255   *
 256   * @global array $wp_taxonomies The registered taxonomies.
 257   *
 258   * @param string $taxonomy Name of taxonomy object to return.
 259   * @return WP_Taxonomy|false The Taxonomy Object or false if $taxonomy doesn't exist.
 260   */
 261  function get_taxonomy( $taxonomy ) {
 262      global $wp_taxonomies;
 263  
 264      if ( ! taxonomy_exists( $taxonomy ) ) {
 265          return false;
 266      }
 267  
 268      return $wp_taxonomies[ $taxonomy ];
 269  }
 270  
 271  /**
 272   * Determines whether the taxonomy name exists.
 273   *
 274   * Formerly is_taxonomy(), introduced in 2.3.0.
 275   *
 276   * For more information on this and similar theme functions, check out
 277   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
 278   * Conditional Tags} article in the Theme Developer Handbook.
 279   *
 280   * @since 3.0.0
 281   *
 282   * @global array $wp_taxonomies The registered taxonomies.
 283   *
 284   * @param string $taxonomy Name of taxonomy object.
 285   * @return bool Whether the taxonomy exists.
 286   */
 287  function taxonomy_exists( $taxonomy ) {
 288      global $wp_taxonomies;
 289  
 290      return isset( $wp_taxonomies[ $taxonomy ] );
 291  }
 292  
 293  /**
 294   * Determines whether the taxonomy object is hierarchical.
 295   *
 296   * Checks to make sure that the taxonomy is an object first. Then Gets the
 297   * object, and finally returns the hierarchical value in the object.
 298   *
 299   * A false return value might also mean that the taxonomy does not exist.
 300   *
 301   * For more information on this and similar theme functions, check out
 302   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
 303   * Conditional Tags} article in the Theme Developer Handbook.
 304   *
 305   * @since 2.3.0
 306   *
 307   * @param string $taxonomy Name of taxonomy object.
 308   * @return bool Whether the taxonomy is hierarchical.
 309   */
 310  function is_taxonomy_hierarchical( $taxonomy ) {
 311      if ( ! taxonomy_exists( $taxonomy ) ) {
 312          return false;
 313      }
 314  
 315      $taxonomy = get_taxonomy( $taxonomy );
 316      return $taxonomy->hierarchical;
 317  }
 318  
 319  /**
 320   * Creates or modifies a taxonomy object.
 321   *
 322   * Note: Do not use before the {@see 'init'} hook.
 323   *
 324   * A simple function for creating or modifying a taxonomy object based on
 325   * the parameters given. If modifying an existing taxonomy object, note
 326   * that the `$object_type` value from the original registration will be
 327   * overwritten.
 328   *
 329   * @since 2.3.0
 330   * @since 4.2.0 Introduced `show_in_quick_edit` argument.
 331   * @since 4.4.0 The `show_ui` argument is now enforced on the term editing screen.
 332   * @since 4.4.0 The `public` argument now controls whether the taxonomy can be queried on the front end.
 333   * @since 4.5.0 Introduced `publicly_queryable` argument.
 334   * @since 4.7.0 Introduced `show_in_rest`, 'rest_base' and 'rest_controller_class'
 335   *              arguments to register the Taxonomy in REST API.
 336   * @since 5.1.0 Introduced `meta_box_sanitize_cb` argument.
 337   * @since 5.4.0 Added the registered taxonomy object as a return value.
 338   * @since 5.5.0 Introduced `default_term` argument.
 339   *
 340   * @global array $wp_taxonomies Registered taxonomies.
 341   *
 342   * @param string       $taxonomy    Taxonomy key, must not exceed 32 characters.
 343   * @param array|string $object_type Object type or array of object types with which the taxonomy should be associated.
 344   * @param array|string $args        {
 345   *     Optional. Array or query string of arguments for registering a taxonomy.
 346   *
 347   *     @type string[]      $labels                An array of labels for this taxonomy. By default, Tag labels are
 348   *                                                used for non-hierarchical taxonomies, and Category labels are used
 349   *                                                for hierarchical taxonomies. See accepted values in
 350   *                                                get_taxonomy_labels(). Default empty array.
 351   *     @type string        $description           A short descriptive summary of what the taxonomy is for. Default empty.
 352   *     @type bool          $public                Whether a taxonomy is intended for use publicly either via
 353   *                                                the admin interface or by front-end users. The default settings
 354   *                                                of `$publicly_queryable`, `$show_ui`, and `$show_in_nav_menus`
 355   *                                                are inherited from `$public`.
 356   *     @type bool          $publicly_queryable    Whether the taxonomy is publicly queryable.
 357   *                                                If not set, the default is inherited from `$public`
 358   *     @type bool          $hierarchical          Whether the taxonomy is hierarchical. Default false.
 359   *     @type bool          $show_ui               Whether to generate and allow a UI for managing terms in this taxonomy in
 360   *                                                the admin. If not set, the default is inherited from `$public`
 361   *                                                (default true).
 362   *     @type bool          $show_in_menu          Whether to show the taxonomy in the admin menu. If true, the taxonomy is
 363   *                                                shown as a submenu of the object type menu. If false, no menu is shown.
 364   *                                                `$show_ui` must be true. If not set, default is inherited from `$show_ui`
 365   *                                                (default true).
 366   *     @type bool          $show_in_nav_menus     Makes this taxonomy available for selection in navigation menus. If not
 367   *                                                set, the default is inherited from `$public` (default true).
 368   *     @type bool          $show_in_rest          Whether to include the taxonomy in the REST API. Set this to true
 369   *                                                for the taxonomy to be available in the block editor.
 370   *     @type string        $rest_base             To change the base url of REST API route. Default is $taxonomy.
 371   *     @type string        $rest_controller_class REST API Controller class name. Default is 'WP_REST_Terms_Controller'.
 372   *     @type bool          $show_tagcloud         Whether to list the taxonomy in the Tag Cloud Widget controls. If not set,
 373   *                                                the default is inherited from `$show_ui` (default true).
 374   *     @type bool          $show_in_quick_edit    Whether to show the taxonomy in the quick/bulk edit panel. It not set,
 375   *                                                the default is inherited from `$show_ui` (default true).
 376   *     @type bool          $show_admin_column     Whether to display a column for the taxonomy on its post type listing
 377   *                                                screens. Default false.
 378   *     @type bool|callable $meta_box_cb           Provide a callback function for the meta box display. If not set,
 379   *                                                post_categories_meta_box() is used for hierarchical taxonomies, and
 380   *                                                post_tags_meta_box() is used for non-hierarchical. If false, no meta
 381   *                                                box is shown.
 382   *     @type callable      $meta_box_sanitize_cb  Callback function for sanitizing taxonomy data saved from a meta
 383   *                                                box. If no callback is defined, an appropriate one is determined
 384   *                                                based on the value of `$meta_box_cb`.
 385   *     @type string[]      $capabilities {
 386   *         Array of capabilities for this taxonomy.
 387   *
 388   *         @type string $manage_terms Default 'manage_categories'.
 389   *         @type string $edit_terms   Default 'manage_categories'.
 390   *         @type string $delete_terms Default 'manage_categories'.
 391   *         @type string $assign_terms Default 'edit_posts'.
 392   *     }
 393   *     @type bool|array    $rewrite {
 394   *         Triggers the handling of rewrites for this taxonomy. Default true, using $taxonomy as slug. To prevent
 395   *         rewrite, set to false. To specify rewrite rules, an array can be passed with any of these keys:
 396   *
 397   *         @type string $slug         Customize the permastruct slug. Default `$taxonomy` key.
 398   *         @type bool   $with_front   Should the permastruct be prepended with WP_Rewrite::$front. Default true.
 399   *         @type bool   $hierarchical Either hierarchical rewrite tag or not. Default false.
 400   *         @type int    $ep_mask      Assign an endpoint mask. Default `EP_NONE`.
 401   *     }
 402   *     @type string|bool   $query_var             Sets the query var key for this taxonomy. Default `$taxonomy` key. If
 403   *                                                false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a
 404   *                                                string, the query `?{query_var}={term_slug}` will be valid.
 405   *     @type callable      $update_count_callback Works much like a hook, in that it will be called when the count is
 406   *                                                updated. Default _update_post_term_count() for taxonomies attached
 407   *                                                to post types, which confirms that the objects are published before
 408   *                                                counting them. Default _update_generic_term_count() for taxonomies
 409   *                                                attached to other object types, such as users.
 410   *     @type string|array  $default_term {
 411   *         Default term to be used for the taxonomy.
 412   *
 413   *         @type string $name         Name of default term.
 414   *         @type string $slug         Slug for default term. Default empty.
 415   *         @type string $description  Description for default term. Default empty.
 416   *     }
 417   *     @type bool          $sort                  Whether terms in this taxonomy should be sorted in the order they are
 418   *                                                provided to `wp_set_object_terms()`. Default null which equates to false.
 419   *     @type array         $args                  Array of arguments to automatically use inside `wp_get_object_terms()`
 420   *                                                for this taxonomy.
 421   *     @type bool          $_builtin              This taxonomy is a "built-in" taxonomy. INTERNAL USE ONLY!
 422   *                                                Default false.
 423   * }
 424   * @return WP_Taxonomy|WP_Error The registered taxonomy object on success, WP_Error object on failure.
 425   */
 426  function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
 427      global $wp_taxonomies;
 428  
 429      if ( ! is_array( $wp_taxonomies ) ) {
 430          $wp_taxonomies = array();
 431      }
 432  
 433      $args = wp_parse_args( $args );
 434  
 435      if ( empty( $taxonomy ) || strlen( $taxonomy ) > 32 ) {
 436          _doing_it_wrong( __FUNCTION__, __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2.0' );
 437          return new WP_Error( 'taxonomy_length_invalid', __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );
 438      }
 439  
 440      $taxonomy_object = new WP_Taxonomy( $taxonomy, $object_type, $args );
 441      $taxonomy_object->add_rewrite_rules();
 442  
 443      $wp_taxonomies[ $taxonomy ] = $taxonomy_object;
 444  
 445      $taxonomy_object->add_hooks();
 446  
 447      // Add default term.
 448      if ( ! empty( $taxonomy_object->default_term ) ) {
 449          $term = term_exists( $taxonomy_object->default_term['name'], $taxonomy );
 450          if ( $term ) {
 451              update_option( 'default_term_' . $taxonomy_object->name, $term['term_id'] );
 452          } else {
 453              $term = wp_insert_term(
 454                  $taxonomy_object->default_term['name'],
 455                  $taxonomy,
 456                  array(
 457                      'slug'        => sanitize_title( $taxonomy_object->default_term['slug'] ),
 458                      'description' => $taxonomy_object->default_term['description'],
 459                  )
 460              );
 461  
 462              // Update `term_id` in options.
 463              if ( ! is_wp_error( $term ) ) {
 464                  update_option( 'default_term_' . $taxonomy_object->name, $term['term_id'] );
 465              }
 466          }
 467      }
 468  
 469      /**
 470       * Fires after a taxonomy is registered.
 471       *
 472       * @since 3.3.0
 473       *
 474       * @param string       $taxonomy    Taxonomy slug.
 475       * @param array|string $object_type Object type or array of object types.
 476       * @param array        $args        Array of taxonomy registration arguments.
 477       */
 478      do_action( 'registered_taxonomy', $taxonomy, $object_type, (array) $taxonomy_object );
 479  
 480      return $taxonomy_object;
 481  }
 482  
 483  /**
 484   * Unregisters a taxonomy.
 485   *
 486   * Can not be used to unregister built-in taxonomies.
 487   *
 488   * @since 4.5.0
 489   *
 490   * @global WP    $wp            Current WordPress environment instance.
 491   * @global array $wp_taxonomies List of taxonomies.
 492   *
 493   * @param string $taxonomy Taxonomy name.
 494   * @return true|WP_Error True on success, WP_Error on failure or if the taxonomy doesn't exist.
 495   */
 496  function unregister_taxonomy( $taxonomy ) {
 497      if ( ! taxonomy_exists( $taxonomy ) ) {
 498          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
 499      }
 500  
 501      $taxonomy_object = get_taxonomy( $taxonomy );
 502  
 503      // Do not allow unregistering internal taxonomies.
 504      if ( $taxonomy_object->_builtin ) {
 505          return new WP_Error( 'invalid_taxonomy', __( 'Unregistering a built-in taxonomy is not allowed.' ) );
 506      }
 507  
 508      global $wp_taxonomies;
 509  
 510      $taxonomy_object->remove_rewrite_rules();
 511      $taxonomy_object->remove_hooks();
 512  
 513      // Remove custom taxonomy default term option.
 514      if ( ! empty( $taxonomy_object->default_term ) ) {
 515          delete_option( 'default_term_' . $taxonomy_object->name );
 516      }
 517  
 518      // Remove the taxonomy.
 519      unset( $wp_taxonomies[ $taxonomy ] );
 520  
 521      /**
 522       * Fires after a taxonomy is unregistered.
 523       *
 524       * @since 4.5.0
 525       *
 526       * @param string $taxonomy Taxonomy name.
 527       */
 528      do_action( 'unregistered_taxonomy', $taxonomy );
 529  
 530      return true;
 531  }
 532  
 533  /**
 534   * Builds an object with all taxonomy labels out of a taxonomy object.
 535   *
 536   * @since 3.0.0
 537   * @since 4.3.0 Added the `no_terms` label.
 538   * @since 4.4.0 Added the `items_list_navigation` and `items_list` labels.
 539   * @since 4.9.0 Added the `most_used` and `back_to_items` labels.
 540   * @since 5.7.0 Added the `filter_by_item` label.
 541   * @since 5.8.0 Added the `item_link` and `item_link_description` labels.
 542   *
 543   * @param WP_Taxonomy $tax Taxonomy object.
 544   * @return object {
 545   *     Taxonomy labels object. The first default value is for non-hierarchical taxonomies
 546   *     (like tags) and the second one is for hierarchical taxonomies (like categories).
 547   *
 548   *     @type string $name                       General name for the taxonomy, usually plural. The same
 549   *                                              as and overridden by `$tax->label`. Default 'Tags'/'Categories'.
 550   *     @type string $singular_name              Name for one object of this taxonomy. Default 'Tag'/'Category'.
 551   *     @type string $search_items               Default 'Search Tags'/'Search Categories'.
 552   *     @type string $popular_items              This label is only used for non-hierarchical taxonomies.
 553   *                                              Default 'Popular Tags'.
 554   *     @type string $all_items                  Default 'All Tags'/'All Categories'.
 555   *     @type string $parent_item                This label is only used for hierarchical taxonomies. Default
 556   *                                              'Parent Category'.
 557   *     @type string $parent_item_colon          The same as `parent_item`, but with colon `:` in the end.
 558   *     @type string $edit_item                  Default 'Edit Tag'/'Edit Category'.
 559   *     @type string $view_item                  Default 'View Tag'/'View Category'.
 560   *     @type string $update_item                Default 'Update Tag'/'Update Category'.
 561   *     @type string $add_new_item               Default 'Add New Tag'/'Add New Category'.
 562   *     @type string $new_item_name              Default 'New Tag Name'/'New Category Name'.
 563   *     @type string $separate_items_with_commas This label is only used for non-hierarchical taxonomies. Default
 564   *                                              'Separate tags with commas', used in the meta box.
 565   *     @type string $add_or_remove_items        This label is only used for non-hierarchical taxonomies. Default
 566   *                                              'Add or remove tags', used in the meta box when JavaScript
 567   *                                              is disabled.
 568   *     @type string $choose_from_most_used      This label is only used on non-hierarchical taxonomies. Default
 569   *                                              'Choose from the most used tags', used in the meta box.
 570   *     @type string $not_found                  Default 'No tags found'/'No categories found', used in
 571   *                                              the meta box and taxonomy list table.
 572   *     @type string $no_terms                   Default 'No tags'/'No categories', used in the posts and media
 573   *                                              list tables.
 574   *     @type string $filter_by_item             This label is only used for hierarchical taxonomies. Default
 575   *                                              'Filter by category', used in the posts list table.
 576   *     @type string $items_list_navigation      Label for the table pagination hidden heading.
 577   *     @type string $items_list                 Label for the table hidden heading.
 578   *     @type string $most_used                  Title for the Most Used tab. Default 'Most Used'.
 579   *     @type string $back_to_items              Label displayed after a term has been updated.
 580   *     @type string $item_link                  Used in the block editor. Title for a navigation link block variation.
 581   *                                              Default 'Tag Link'/'Category Link'.
 582   *     @type string $item_link_description      Used in the block editor. Description for a navigation link block
 583   *                                              variation. Default 'A link to a tag'/'A link to a category'.
 584   * }
 585   */
 586  function get_taxonomy_labels( $tax ) {
 587      $tax->labels = (array) $tax->labels;
 588  
 589      if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) ) {
 590          $tax->labels['separate_items_with_commas'] = $tax->helps;
 591      }
 592  
 593      if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) ) {
 594          $tax->labels['not_found'] = $tax->no_tagcloud;
 595      }
 596  
 597      $nohier_vs_hier_defaults = array(
 598          'name'                       => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ),
 599          'singular_name'              => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ),
 600          'search_items'               => array( __( 'Search Tags' ), __( 'Search Categories' ) ),
 601          'popular_items'              => array( __( 'Popular Tags' ), null ),
 602          'all_items'                  => array( __( 'All Tags' ), __( 'All Categories' ) ),
 603          'parent_item'                => array( null, __( 'Parent Category' ) ),
 604          'parent_item_colon'          => array( null, __( 'Parent Category:' ) ),
 605          'edit_item'                  => array( __( 'Edit Tag' ), __( 'Edit Category' ) ),
 606          'view_item'                  => array( __( 'View Tag' ), __( 'View Category' ) ),
 607          'update_item'                => array( __( 'Update Tag' ), __( 'Update Category' ) ),
 608          'add_new_item'               => array( __( 'Add New Tag' ), __( 'Add New Category' ) ),
 609          'new_item_name'              => array( __( 'New Tag Name' ), __( 'New Category Name' ) ),
 610          'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ),
 611          'add_or_remove_items'        => array( __( 'Add or remove tags' ), null ),
 612          'choose_from_most_used'      => array( __( 'Choose from the most used tags' ), null ),
 613          'not_found'                  => array( __( 'No tags found.' ), __( 'No categories found.' ) ),
 614          'no_terms'                   => array( __( 'No tags' ), __( 'No categories' ) ),
 615          'filter_by_item'             => array( null, __( 'Filter by category' ) ),
 616          'items_list_navigation'      => array( __( 'Tags list navigation' ), __( 'Categories list navigation' ) ),
 617          'items_list'                 => array( __( 'Tags list' ), __( 'Categories list' ) ),
 618          /* translators: Tab heading when selecting from the most used terms. */
 619          'most_used'                  => array( _x( 'Most Used', 'tags' ), _x( 'Most Used', 'categories' ) ),
 620          'back_to_items'              => array( __( '&larr; Go to Tags' ), __( '&larr; Go to Categories' ) ),
 621          'item_link'                  => array(
 622              _x( 'Tag Link', 'navigation link block title' ),
 623              _x( 'Category Link', 'navigation link block description' ),
 624          ),
 625          'item_link_description'      => array(
 626              _x( 'A link to a tag.', 'navigation link block description' ),
 627              _x( 'A link to a category.', 'navigation link block description' ),
 628          ),
 629      );
 630  
 631      $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
 632  
 633      $labels = _get_custom_object_labels( $tax, $nohier_vs_hier_defaults );
 634  
 635      $taxonomy = $tax->name;
 636  
 637      $default_labels = clone $labels;
 638  
 639      /**
 640       * Filters the labels of a specific taxonomy.
 641       *
 642       * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
 643       *
 644       * Possible hook names include:
 645       *
 646       *  - `taxonomy_labels_category`
 647       *  - `taxonomy_labels_post_tag`
 648       *
 649       * @since 4.4.0
 650       *
 651       * @see get_taxonomy_labels() for the full list of taxonomy labels.
 652       *
 653       * @param object $labels Object with labels for the taxonomy as member variables.
 654       */
 655      $labels = apply_filters( "taxonomy_labels_{$taxonomy}", $labels );
 656  
 657      // Ensure that the filtered labels contain all required default values.
 658      $labels = (object) array_merge( (array) $default_labels, (array) $labels );
 659  
 660      return $labels;
 661  }
 662  
 663  /**
 664   * Add an already registered taxonomy to an object type.
 665   *
 666   * @since 3.0.0
 667   *
 668   * @global array $wp_taxonomies The registered taxonomies.
 669   *
 670   * @param string $taxonomy    Name of taxonomy object.
 671   * @param string $object_type Name of the object type.
 672   * @return bool True if successful, false if not.
 673   */
 674  function register_taxonomy_for_object_type( $taxonomy, $object_type ) {
 675      global $wp_taxonomies;
 676  
 677      if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
 678          return false;
 679      }
 680  
 681      if ( ! get_post_type_object( $object_type ) ) {
 682          return false;
 683      }
 684  
 685      if ( ! in_array( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true ) ) {
 686          $wp_taxonomies[ $taxonomy ]->object_type[] = $object_type;
 687      }
 688  
 689      // Filter out empties.
 690      $wp_taxonomies[ $taxonomy ]->object_type = array_filter( $wp_taxonomies[ $taxonomy ]->object_type );
 691  
 692      /**
 693       * Fires after a taxonomy is registered for an object type.
 694       *
 695       * @since 5.1.0
 696       *
 697       * @param string $taxonomy    Taxonomy name.
 698       * @param string $object_type Name of the object type.
 699       */
 700      do_action( 'registered_taxonomy_for_object_type', $taxonomy, $object_type );
 701  
 702      return true;
 703  }
 704  
 705  /**
 706   * Remove an already registered taxonomy from an object type.
 707   *
 708   * @since 3.7.0
 709   *
 710   * @global array $wp_taxonomies The registered taxonomies.
 711   *
 712   * @param string $taxonomy    Name of taxonomy object.
 713   * @param string $object_type Name of the object type.
 714   * @return bool True if successful, false if not.
 715   */
 716  function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
 717      global $wp_taxonomies;
 718  
 719      if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
 720          return false;
 721      }
 722  
 723      if ( ! get_post_type_object( $object_type ) ) {
 724          return false;
 725      }
 726  
 727      $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
 728      if ( false === $key ) {
 729          return false;
 730      }
 731  
 732      unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );
 733  
 734      /**
 735       * Fires after a taxonomy is unregistered for an object type.
 736       *
 737       * @since 5.1.0
 738       *
 739       * @param string $taxonomy    Taxonomy name.
 740       * @param string $object_type Name of the object type.
 741       */
 742      do_action( 'unregistered_taxonomy_for_object_type', $taxonomy, $object_type );
 743  
 744      return true;
 745  }
 746  
 747  //
 748  // Term API.
 749  //
 750  
 751  /**
 752   * Retrieve object_ids of valid taxonomy and term.
 753   *
 754   * The strings of $taxonomies must exist before this function will continue.
 755   * On failure of finding a valid taxonomy, it will return a WP_Error class,
 756   * kind of like Exceptions in PHP 5, except you can't catch them. Even so,
 757   * you can still test for the WP_Error class and get the error message.
 758   *
 759   * The $terms aren't checked the same as $taxonomies, but still need to exist
 760   * for $object_ids to be returned.
 761   *
 762   * It is possible to change the order that object_ids is returned by either
 763   * using PHP sort family functions or using the database by using $args with
 764   * either ASC or DESC array. The value should be in the key named 'order'.
 765   *
 766   * @since 2.3.0
 767   *
 768   * @global wpdb $wpdb WordPress database abstraction object.
 769   *
 770   * @param int|array    $term_ids   Term ID or array of term IDs of terms that will be used.
 771   * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names.
 772   * @param array|string $args       Change the order of the object_ids, either ASC or DESC.
 773   * @return array|WP_Error An array of $object_ids on success, WP_Error if the taxonomy does not exist.
 774   */
 775  function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) {
 776      global $wpdb;
 777  
 778      if ( ! is_array( $term_ids ) ) {
 779          $term_ids = array( $term_ids );
 780      }
 781      if ( ! is_array( $taxonomies ) ) {
 782          $taxonomies = array( $taxonomies );
 783      }
 784      foreach ( (array) $taxonomies as $taxonomy ) {
 785          if ( ! taxonomy_exists( $taxonomy ) ) {
 786              return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
 787          }
 788      }
 789  
 790      $defaults = array( 'order' => 'ASC' );
 791      $args     = wp_parse_args( $args, $defaults );
 792  
 793      $order = ( 'desc' === strtolower( $args['order'] ) ) ? 'DESC' : 'ASC';
 794  
 795      $term_ids = array_map( 'intval', $term_ids );
 796  
 797      $taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
 798      $term_ids   = "'" . implode( "', '", $term_ids ) . "'";
 799  
 800      $sql = "SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order";
 801  
 802      $last_changed = wp_cache_get_last_changed( 'terms' );
 803      $cache_key    = 'get_objects_in_term:' . md5( $sql ) . ":$last_changed";
 804      $cache        = wp_cache_get( $cache_key, 'terms' );
 805      if ( false === $cache ) {
 806          $object_ids = $wpdb->get_col( $sql );
 807          wp_cache_set( $cache_key, $object_ids, 'terms' );
 808      } else {
 809          $object_ids = (array) $cache;
 810      }
 811  
 812      if ( ! $object_ids ) {
 813          return array();
 814      }
 815      return $object_ids;
 816  }
 817  
 818  /**
 819   * Given a taxonomy query, generates SQL to be appended to a main query.
 820   *
 821   * @since 3.1.0
 822   *
 823   * @see WP_Tax_Query
 824   *
 825   * @param array  $tax_query         A compact tax query
 826   * @param string $primary_table
 827   * @param string $primary_id_column
 828   * @return array
 829   */
 830  function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) {
 831      $tax_query_obj = new WP_Tax_Query( $tax_query );
 832      return $tax_query_obj->get_sql( $primary_table, $primary_id_column );
 833  }
 834  
 835  /**
 836   * Get all Term data from database by Term ID.
 837   *
 838   * The usage of the get_term function is to apply filters to a term object. It
 839   * is possible to get a term object from the database before applying the
 840   * filters.
 841   *
 842   * $term ID must be part of $taxonomy, to get from the database. Failure, might
 843   * be able to be captured by the hooks. Failure would be the same value as $wpdb
 844   * returns for the get_row method.
 845   *
 846   * There are two hooks, one is specifically for each term, named 'get_term', and
 847   * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the
 848   * term object, and the taxonomy name as parameters. Both hooks are expected to
 849   * return a Term object.
 850   *
 851   * {@see 'get_term'} hook - Takes two parameters the term Object and the taxonomy name.
 852   * Must return term object. Used in get_term() as a catch-all filter for every
 853   * $term.
 854   *
 855   * {@see 'get_$taxonomy'} hook - Takes two parameters the term Object and the taxonomy
 856   * name. Must return term object. $taxonomy will be the taxonomy name, so for
 857   * example, if 'category', it would be 'get_category' as the filter name. Useful
 858   * for custom taxonomies or plugging into default taxonomies.
 859   *
 860   * @todo Better formatting for DocBlock
 861   *
 862   * @since 2.3.0
 863   * @since 4.4.0 Converted to return a WP_Term object if `$output` is `OBJECT`.
 864   *              The `$taxonomy` parameter was made optional.
 865   *
 866   * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
 867   *
 868   * @param int|WP_Term|object $term     If integer, term data will be fetched from the database,
 869   *                                     or from the cache if available.
 870   *                                     If stdClass object (as in the results of a database query),
 871   *                                     will apply filters and return a `WP_Term` object with the `$term` data.
 872   *                                     If `WP_Term`, will return `$term`.
 873   * @param string             $taxonomy Optional. Taxonomy name that `$term` is part of.
 874   * @param string             $output   Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 875   *                                     correspond to a WP_Term object, an associative array, or a numeric array,
 876   *                                     respectively. Default OBJECT.
 877   * @param string             $filter   Optional. How to sanitize term fields. Default 'raw'.
 878   * @return WP_Term|array|WP_Error|null WP_Term instance (or array) on success, depending on the `$output` value.
 879   *                                     WP_Error if `$taxonomy` does not exist. Null for miscellaneous failure.
 880   */
 881  function get_term( $term, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
 882      if ( empty( $term ) ) {
 883          return new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
 884      }
 885  
 886      if ( $taxonomy && ! taxonomy_exists( $taxonomy ) ) {
 887          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
 888      }
 889  
 890      if ( $term instanceof WP_Term ) {
 891          $_term = $term;
 892      } elseif ( is_object( $term ) ) {
 893          if ( empty( $term->filter ) || 'raw' === $term->filter ) {
 894              $_term = sanitize_term( $term, $taxonomy, 'raw' );
 895              $_term = new WP_Term( $_term );
 896          } else {
 897              $_term = WP_Term::get_instance( $term->term_id );
 898          }
 899      } else {
 900          $_term = WP_Term::get_instance( $term, $taxonomy );
 901      }
 902  
 903      if ( is_wp_error( $_term ) ) {
 904          return $_term;
 905      } elseif ( ! $_term ) {
 906          return null;
 907      }
 908  
 909      // Ensure for filters that this is not empty.
 910      $taxonomy = $_term->taxonomy;
 911  
 912      /**
 913       * Filters a taxonomy term object.
 914       *
 915       * The {@see 'get_$taxonomy'} hook is also available for targeting a specific
 916       * taxonomy.
 917       *
 918       * @since 2.3.0
 919       * @since 4.4.0 `$_term` is now a `WP_Term` object.
 920       *
 921       * @param WP_Term $_term    Term object.
 922       * @param string  $taxonomy The taxonomy slug.
 923       */
 924      $_term = apply_filters( 'get_term', $_term, $taxonomy );
 925  
 926      /**
 927       * Filters a taxonomy term object.
 928       *
 929       * The dynamic portion of the filter name, `$taxonomy`, refers
 930       * to the slug of the term's taxonomy.
 931       *
 932       * @since 2.3.0
 933       * @since 4.4.0 `$_term` is now a `WP_Term` object.
 934       *
 935       * @param WP_Term $_term    Term object.
 936       * @param string  $taxonomy The taxonomy slug.
 937       */
 938      $_term = apply_filters( "get_{$taxonomy}", $_term, $taxonomy );
 939  
 940      // Bail if a filter callback has changed the type of the `$_term` object.
 941      if ( ! ( $_term instanceof WP_Term ) ) {
 942          return $_term;
 943      }
 944  
 945      // Sanitize term, according to the specified filter.
 946      $_term->filter( $filter );
 947  
 948      if ( ARRAY_A === $output ) {
 949          return $_term->to_array();
 950      } elseif ( ARRAY_N === $output ) {
 951          return array_values( $_term->to_array() );
 952      }
 953  
 954      return $_term;
 955  }
 956  
 957  /**
 958   * Get all Term data from database by Term field and data.
 959   *
 960   * Warning: $value is not escaped for 'name' $field. You must do it yourself, if
 961   * required.
 962   *
 963   * The default $field is 'id', therefore it is possible to also use null for
 964   * field, but not recommended that you do so.
 965   *
 966   * If $value does not exist, the return value will be false. If $taxonomy exists
 967   * and $field and $value combinations exist, the Term will be returned.
 968   *
 969   * This function will always return the first term that matches the `$field`-
 970   * `$value`-`$taxonomy` combination specified in the parameters. If your query
 971   * is likely to match more than one term (as is likely to be the case when
 972   * `$field` is 'name', for example), consider using get_terms() instead; that
 973   * way, you will get all matching terms, and can provide your own logic for
 974   * deciding which one was intended.
 975   *
 976   * @todo Better formatting for DocBlock.
 977   *
 978   * @since 2.3.0
 979   * @since 4.4.0 `$taxonomy` is optional if `$field` is 'term_taxonomy_id'. Converted to return
 980   *              a WP_Term object if `$output` is `OBJECT`.
 981   * @since 5.5.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
 982   *
 983   * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param.
 984   *
 985   * @param string     $field    Either 'slug', 'name', 'id' or 'ID' (term_id), or 'term_taxonomy_id'.
 986   * @param string|int $value    Search for this term value.
 987   * @param string     $taxonomy Taxonomy name. Optional, if `$field` is 'term_taxonomy_id'.
 988   * @param string     $output   Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 989   *                             correspond to a WP_Term object, an associative array, or a numeric array,
 990   *                             respectively. Default OBJECT.
 991   * @param string     $filter   Optional. How to sanitize term fields. Default 'raw'.
 992   * @return WP_Term|array|false WP_Term instance (or array) on success, depending on the `$output` value.
 993   *                             False if `$taxonomy` does not exist or `$term` was not found.
 994   */
 995  function get_term_by( $field, $value, $taxonomy = '', $output = OBJECT, $filter = 'raw' ) {
 996  
 997      // 'term_taxonomy_id' lookups don't require taxonomy checks.
 998      if ( 'term_taxonomy_id' !== $field && ! taxonomy_exists( $taxonomy ) ) {
 999          return false;
1000      }
1001  
1002      // No need to perform a query for empty 'slug' or 'name'.
1003      if ( 'slug' === $field || 'name' === $field ) {
1004          $value = (string) $value;
1005  
1006          if ( 0 === strlen( $value ) ) {
1007              return false;
1008          }
1009      }
1010  
1011      if ( 'id' === $field || 'ID' === $field || 'term_id' === $field ) {
1012          $term = get_term( (int) $value, $taxonomy, $output, $filter );
1013          if ( is_wp_error( $term ) || null === $term ) {
1014              $term = false;
1015          }
1016          return $term;
1017      }
1018  
1019      $args = array(
1020          'get'                    => 'all',
1021          'number'                 => 1,
1022          'taxonomy'               => $taxonomy,
1023          'update_term_meta_cache' => false,
1024          'orderby'                => 'none',
1025          'suppress_filter'        => true,
1026      );
1027  
1028      switch ( $field ) {
1029          case 'slug':
1030              $args['slug'] = $value;
1031              break;
1032          case 'name':
1033              $args['name'] = $value;
1034              break;
1035          case 'term_taxonomy_id':
1036              $args['term_taxonomy_id'] = $value;
1037              unset( $args['taxonomy'] );
1038              break;
1039          default:
1040              return false;
1041      }
1042  
1043      $terms = get_terms( $args );
1044      if ( is_wp_error( $terms ) || empty( $terms ) ) {
1045          return false;
1046      }
1047  
1048      $term = array_shift( $terms );
1049  
1050      // In the case of 'term_taxonomy_id', override the provided `$taxonomy` with whatever we find in the DB.
1051      if ( 'term_taxonomy_id' === $field ) {
1052          $taxonomy = $term->taxonomy;
1053      }
1054  
1055      return get_term( $term, $taxonomy, $output, $filter );
1056  }
1057  
1058  /**
1059   * Merge all term children into a single array of their IDs.
1060   *
1061   * This recursive function will merge all of the children of $term into the same
1062   * array of term IDs. Only useful for taxonomies which are hierarchical.
1063   *
1064   * Will return an empty array if $term does not exist in $taxonomy.
1065   *
1066   * @since 2.3.0
1067   *
1068   * @param int    $term_id  ID of Term to get children.
1069   * @param string $taxonomy Taxonomy Name.
1070   * @return array|WP_Error List of Term IDs. WP_Error returned if `$taxonomy` does not exist.
1071   */
1072  function get_term_children( $term_id, $taxonomy ) {
1073      if ( ! taxonomy_exists( $taxonomy ) ) {
1074          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
1075      }
1076  
1077      $term_id = (int) $term_id;
1078  
1079      $terms = _get_term_hierarchy( $taxonomy );
1080  
1081      if ( ! isset( $terms[ $term_id ] ) ) {
1082          return array();
1083      }
1084  
1085      $children = $terms[ $term_id ];
1086  
1087      foreach ( (array) $terms[ $term_id ] as $child ) {
1088          if ( $term_id === $child ) {
1089              continue;
1090          }
1091  
1092          if ( isset( $terms[ $child ] ) ) {
1093              $children = array_merge( $children, get_term_children( $child, $taxonomy ) );
1094          }
1095      }
1096  
1097      return $children;
1098  }
1099  
1100  /**
1101   * Get sanitized Term field.
1102   *
1103   * The function is for contextual reasons and for simplicity of usage.
1104   *
1105   * @since 2.3.0
1106   * @since 4.4.0 The `$taxonomy` parameter was made optional. `$term` can also now accept a WP_Term object.
1107   *
1108   * @see sanitize_term_field()
1109   *
1110   * @param string      $field    Term field to fetch.
1111   * @param int|WP_Term $term     Term ID or object.
1112   * @param string      $taxonomy Optional. Taxonomy Name. Default empty.
1113   * @param string      $context  Optional. How to sanitize term fields. Look at sanitize_term_field() for available options.
1114   *                              Default 'display'.
1115   * @return string|int|null|WP_Error Will return an empty string if $term is not an object or if $field is not set in $term.
1116   */
1117  function get_term_field( $field, $term, $taxonomy = '', $context = 'display' ) {
1118      $term = get_term( $term, $taxonomy );
1119      if ( is_wp_error( $term ) ) {
1120          return $term;
1121      }
1122  
1123      if ( ! is_object( $term ) ) {
1124          return '';
1125      }
1126  
1127      if ( ! isset( $term->$field ) ) {
1128          return '';
1129      }
1130  
1131      return sanitize_term_field( $field, $term->$field, $term->term_id, $term->taxonomy, $context );
1132  }
1133  
1134  /**
1135   * Sanitizes Term for editing.
1136   *
1137   * Return value is sanitize_term() and usage is for sanitizing the term for
1138   * editing. Function is for contextual and simplicity.
1139   *
1140   * @since 2.3.0
1141   *
1142   * @param int|object $id       Term ID or object.
1143   * @param string     $taxonomy Taxonomy name.
1144   * @return string|int|null|WP_Error Will return empty string if $term is not an object.
1145   */
1146  function get_term_to_edit( $id, $taxonomy ) {
1147      $term = get_term( $id, $taxonomy );
1148  
1149      if ( is_wp_error( $term ) ) {
1150          return $term;
1151      }
1152  
1153      if ( ! is_object( $term ) ) {
1154          return '';
1155      }
1156  
1157      return sanitize_term( $term, $taxonomy, 'edit' );
1158  }
1159  
1160  /**
1161   * Retrieves the terms in a given taxonomy or list of taxonomies.
1162   *
1163   * You can fully inject any customizations to the query before it is sent, as
1164   * well as control the output with a filter.
1165   *
1166   * The return type varies depending on the value passed to `$args['fields']`. See
1167   * WP_Term_Query::get_terms() for details. In all cases, a `WP_Error` object will
1168   * be returned if an invalid taxonomy is requested.
1169   *
1170   * The {@see 'get_terms'} filter will be called when the cache has the term and will
1171   * pass the found term along with the array of $taxonomies and array of $args.
1172   * This filter is also called before the array of terms is passed and will pass
1173   * the array of terms, along with the $taxonomies and $args.
1174   *
1175   * The {@see 'list_terms_exclusions'} filter passes the compiled exclusions along with
1176   * the $args.
1177   *
1178   * The {@see 'get_terms_orderby'} filter passes the `ORDER BY` clause for the query
1179   * along with the $args array.
1180   *
1181   * Prior to 4.5.0, the first parameter of `get_terms()` was a taxonomy or list of taxonomies:
1182   *
1183   *     $terms = get_terms( 'post_tag', array(
1184   *         'hide_empty' => false,
1185   *     ) );
1186   *
1187   * Since 4.5.0, taxonomies should be passed via the 'taxonomy' argument in the `$args` array:
1188   *
1189   *     $terms = get_terms( array(
1190   *         'taxonomy' => 'post_tag',
1191   *         'hide_empty' => false,
1192   *     ) );
1193   *
1194   * @since 2.3.0
1195   * @since 4.2.0 Introduced 'name' and 'childless' parameters.
1196   * @since 4.4.0 Introduced the ability to pass 'term_id' as an alias of 'id' for the `orderby` parameter.
1197   *              Introduced the 'meta_query' and 'update_term_meta_cache' parameters. Converted to return
1198   *              a list of WP_Term objects.
1199   * @since 4.5.0 Changed the function signature so that the `$args` array can be provided as the first parameter.
1200   *              Introduced 'meta_key' and 'meta_value' parameters. Introduced the ability to order results by metadata.
1201   * @since 4.8.0 Introduced 'suppress_filter' parameter.
1202   *
1203   * @internal The `$deprecated` parameter is parsed for backward compatibility only.
1204   *
1205   * @param array|string $args       Optional. Array or string of arguments. See WP_Term_Query::__construct()
1206   *                                 for information on accepted arguments. Default empty array.
1207   * @param array|string $deprecated Optional. Argument array, when using the legacy function parameter format.
1208   *                                 If present, this parameter will be interpreted as `$args`, and the first
1209   *                                 function parameter will be parsed as a taxonomy or array of taxonomies.
1210   *                                 Default empty.
1211   * @return WP_Term[]|int[]|string[]|string|WP_Error Array of terms, a count thereof as a numeric string,
1212   *                                                  or WP_Error if any of the taxonomies do not exist.
1213   *                                                  See the function description for more information.
1214   */
1215  function get_terms( $args = array(), $deprecated = '' ) {
1216      $term_query = new WP_Term_Query();
1217  
1218      $defaults = array(
1219          'suppress_filter' => false,
1220      );
1221  
1222      /*
1223       * Legacy argument format ($taxonomy, $args) takes precedence.
1224       *
1225       * We detect legacy argument format by checking if
1226       * (a) a second non-empty parameter is passed, or
1227       * (b) the first parameter shares no keys with the default array (ie, it's a list of taxonomies)
1228       */
1229      $_args          = wp_parse_args( $args );
1230      $key_intersect  = array_intersect_key( $term_query->query_var_defaults, (array) $_args );
1231      $do_legacy_args = $deprecated || empty( $key_intersect );
1232  
1233      if ( $do_legacy_args ) {
1234          $taxonomies       = (array) $args;
1235          $args             = wp_parse_args( $deprecated, $defaults );
1236          $args['taxonomy'] = $taxonomies;
1237      } else {
1238          $args = wp_parse_args( $args, $defaults );
1239          if ( isset( $args['taxonomy'] ) && null !== $args['taxonomy'] ) {
1240              $args['taxonomy'] = (array) $args['taxonomy'];
1241          }
1242      }
1243  
1244      if ( ! empty( $args['taxonomy'] ) ) {
1245          foreach ( $args['taxonomy'] as $taxonomy ) {
1246              if ( ! taxonomy_exists( $taxonomy ) ) {
1247                  return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
1248              }
1249          }
1250      }
1251  
1252      // Don't pass suppress_filter to WP_Term_Query.
1253      $suppress_filter = $args['suppress_filter'];
1254      unset( $args['suppress_filter'] );
1255  
1256      $terms = $term_query->query( $args );
1257  
1258      // Count queries are not filtered, for legacy reasons.
1259      if ( ! is_array( $terms ) ) {
1260          return $terms;
1261      }
1262  
1263      if ( $suppress_filter ) {
1264          return $terms;
1265      }
1266  
1267      /**
1268       * Filters the found terms.
1269       *
1270       * @since 2.3.0
1271       * @since 4.6.0 Added the `$term_query` parameter.
1272       *
1273       * @param array         $terms      Array of found terms.
1274       * @param array         $taxonomies An array of taxonomies.
1275       * @param array         $args       An array of get_terms() arguments.
1276       * @param WP_Term_Query $term_query The WP_Term_Query object.
1277       */
1278      return apply_filters( 'get_terms', $terms, $term_query->query_vars['taxonomy'], $term_query->query_vars, $term_query );
1279  }
1280  
1281  /**
1282   * Adds metadata to a term.
1283   *
1284   * @since 4.4.0
1285   *
1286   * @param int    $term_id    Term ID.
1287   * @param string $meta_key   Metadata name.
1288   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1289   * @param bool   $unique     Optional. Whether the same key should not be added.
1290   *                           Default false.
1291   * @return int|false|WP_Error Meta ID on success, false on failure.
1292   *                            WP_Error when term_id is ambiguous between taxonomies.
1293   */
1294  function add_term_meta( $term_id, $meta_key, $meta_value, $unique = false ) {
1295      if ( wp_term_is_shared( $term_id ) ) {
1296          return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.' ), $term_id );
1297      }
1298  
1299      return add_metadata( 'term', $term_id, $meta_key, $meta_value, $unique );
1300  }
1301  
1302  /**
1303   * Removes metadata matching criteria from a term.
1304   *
1305   * @since 4.4.0
1306   *
1307   * @param int    $term_id    Term ID.
1308   * @param string $meta_key   Metadata name.
1309   * @param mixed  $meta_value Optional. Metadata value. If provided,
1310   *                           rows will only be removed that match the value.
1311   *                           Must be serializable if non-scalar. Default empty.
1312   * @return bool True on success, false on failure.
1313   */
1314  function delete_term_meta( $term_id, $meta_key, $meta_value = '' ) {
1315      return delete_metadata( 'term', $term_id, $meta_key, $meta_value );
1316  }
1317  
1318  /**
1319   * Retrieves metadata for a term.
1320   *
1321   * @since 4.4.0
1322   *
1323   * @param int    $term_id Term ID.
1324   * @param string $key     Optional. The meta key to retrieve. By default,
1325   *                        returns data for all keys. Default empty.
1326   * @param bool   $single  Optional. Whether to return a single value.
1327   *                        This parameter has no effect if `$key` is not specified.
1328   *                        Default false.
1329   * @return mixed An array of values if `$single` is false.
1330   *               The value of the meta field if `$single` is true.
1331   *               False for an invalid `$term_id` (non-numeric, zero, or negative value).
1332   *               An empty string if a valid but non-existing term ID is passed.
1333   */
1334  function get_term_meta( $term_id, $key = '', $single = false ) {
1335      return get_metadata( 'term', $term_id, $key, $single );
1336  }
1337  
1338  /**
1339   * Updates term metadata.
1340   *
1341   * Use the `$prev_value` parameter to differentiate between meta fields with the same key and term ID.
1342   *
1343   * If the meta field for the term does not exist, it will be added.
1344   *
1345   * @since 4.4.0
1346   *
1347   * @param int    $term_id    Term ID.
1348   * @param string $meta_key   Metadata key.
1349   * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1350   * @param mixed  $prev_value Optional. Previous value to check before updating.
1351   *                           If specified, only update existing metadata entries with
1352   *                           this value. Otherwise, update all entries. Default empty.
1353   * @return int|bool|WP_Error Meta ID if the key didn't exist. true on successful update,
1354   *                           false on failure or if the value passed to the function
1355   *                           is the same as the one that is already in the database.
1356   *                           WP_Error when term_id is ambiguous between taxonomies.
1357   */
1358  function update_term_meta( $term_id, $meta_key, $meta_value, $prev_value = '' ) {
1359      if ( wp_term_is_shared( $term_id ) ) {
1360          return new WP_Error( 'ambiguous_term_id', __( 'Term meta cannot be added to terms that are shared between taxonomies.' ), $term_id );
1361      }
1362  
1363      return update_metadata( 'term', $term_id, $meta_key, $meta_value, $prev_value );
1364  }
1365  
1366  /**
1367   * Updates metadata cache for list of term IDs.
1368   *
1369   * Performs SQL query to retrieve all metadata for the terms matching `$term_ids` and stores them in the cache.
1370   * Subsequent calls to `get_term_meta()` will not need to query the database.
1371   *
1372   * @since 4.4.0
1373   *
1374   * @param array $term_ids List of term IDs.
1375   * @return array|false An array of metadata on success, false if there is nothing to update.
1376   */
1377  function update_termmeta_cache( $term_ids ) {
1378      return update_meta_cache( 'term', $term_ids );
1379  }
1380  
1381  /**
1382   * Get all meta data, including meta IDs, for the given term ID.
1383   *
1384   * @since 4.9.0
1385   *
1386   * @global wpdb $wpdb WordPress database abstraction object.
1387   *
1388   * @param int $term_id Term ID.
1389   * @return array|false Array with meta data, or false when the meta table is not installed.
1390   */
1391  function has_term_meta( $term_id ) {
1392      $check = wp_check_term_meta_support_prefilter( null );
1393      if ( null !== $check ) {
1394          return $check;
1395      }
1396  
1397      global $wpdb;
1398  
1399      return $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value, meta_id, term_id FROM $wpdb->termmeta WHERE term_id = %d ORDER BY meta_key,meta_id", $term_id ), ARRAY_A );
1400  }
1401  
1402  /**
1403   * Registers a meta key for terms.
1404   *
1405   * @since 4.9.8
1406   *
1407   * @param string $taxonomy Taxonomy to register a meta key for. Pass an empty string
1408   *                         to register the meta key across all existing taxonomies.
1409   * @param string $meta_key The meta key to register.
1410   * @param array  $args     Data used to describe the meta key when registered. See
1411   *                         {@see register_meta()} for a list of supported arguments.
1412   * @return bool True if the meta key was successfully registered, false if not.
1413   */
1414  function register_term_meta( $taxonomy, $meta_key, array $args ) {
1415      $args['object_subtype'] = $taxonomy;
1416  
1417      return register_meta( 'term', $meta_key, $args );
1418  }
1419  
1420  /**
1421   * Unregisters a meta key for terms.
1422   *
1423   * @since 4.9.8
1424   *
1425   * @param string $taxonomy Taxonomy the meta key is currently registered for. Pass
1426   *                         an empty string if the meta key is registered across all
1427   *                         existing taxonomies.
1428   * @param string $meta_key The meta key to unregister.
1429   * @return bool True on success, false if the meta key was not previously registered.
1430   */
1431  function unregister_term_meta( $taxonomy, $meta_key ) {
1432      return unregister_meta_key( 'term', $meta_key, $taxonomy );
1433  }
1434  
1435  /**
1436   * Determines whether a taxonomy term exists.
1437   *
1438   * Formerly is_term(), introduced in 2.3.0.
1439   *
1440   * For more information on this and similar theme functions, check out
1441   * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
1442   * Conditional Tags} article in the Theme Developer Handbook.
1443   *
1444   * @since 3.0.0
1445   *
1446   * @global wpdb $wpdb WordPress database abstraction object.
1447   *
1448   * @param int|string $term     The term to check. Accepts term ID, slug, or name.
1449   * @param string     $taxonomy Optional. The taxonomy name to use.
1450   * @param int        $parent   Optional. ID of parent term under which to confine the exists search.
1451   * @return mixed Returns null if the term does not exist.
1452   *               Returns the term ID if no taxonomy is specified and the term ID exists.
1453   *               Returns an array of the term ID and the term taxonomy ID if the taxonomy is specified and the pairing exists.
1454   *               Returns 0 if term ID 0 is passed to the function.
1455   */
1456  function term_exists( $term, $taxonomy = '', $parent = null ) {
1457      global $wpdb;
1458  
1459      $select     = "SELECT term_id FROM $wpdb->terms as t WHERE ";
1460      $tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE ";
1461  
1462      if ( is_int( $term ) ) {
1463          if ( 0 === $term ) {
1464              return 0;
1465          }
1466          $where = 't.term_id = %d';
1467          if ( ! empty( $taxonomy ) ) {
1468              // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
1469              return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . ' AND tt.taxonomy = %s', $term, $taxonomy ), ARRAY_A );
1470          } else {
1471              return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) );
1472          }
1473      }
1474  
1475      $term = trim( wp_unslash( $term ) );
1476      $slug = sanitize_title( $term );
1477  
1478      $where             = 't.slug = %s';
1479      $else_where        = 't.name = %s';
1480      $where_fields      = array( $slug );
1481      $else_where_fields = array( $term );
1482      $orderby           = 'ORDER BY t.term_id ASC';
1483      $limit             = 'LIMIT 1';
1484      if ( ! empty( $taxonomy ) ) {
1485          if ( is_numeric( $parent ) ) {
1486              $parent              = (int) $parent;
1487              $where_fields[]      = $parent;
1488              $else_where_fields[] = $parent;
1489              $where              .= ' AND tt.parent = %d';
1490              $else_where         .= ' AND tt.parent = %d';
1491          }
1492  
1493          $where_fields[]      = $taxonomy;
1494          $else_where_fields[] = $taxonomy;
1495  
1496          $result = $wpdb->get_row( $wpdb->prepare( "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s $orderby $limit", $where_fields ), ARRAY_A );
1497          if ( $result ) {
1498              return $result;
1499          }
1500  
1501          return $wpdb->get_row( $wpdb->prepare( "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s $orderby $limit", $else_where_fields ), ARRAY_A );
1502      }
1503  
1504      // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
1505      $result = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms as t WHERE $where $orderby $limit", $where_fields ) );
1506      if ( $result ) {
1507          return $result;
1508      }
1509  
1510      // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
1511      return $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms as t WHERE $else_where $orderby $limit", $else_where_fields ) );
1512  }
1513  
1514  /**
1515   * Check if a term is an ancestor of another term.
1516   *
1517   * You can use either an ID or the term object for both parameters.
1518   *
1519   * @since 3.4.0
1520   *
1521   * @param int|object $term1    ID or object to check if this is the parent term.
1522   * @param int|object $term2    The child term.
1523   * @param string     $taxonomy Taxonomy name that $term1 and `$term2` belong to.
1524   * @return bool Whether `$term2` is a child of `$term1`.
1525   */
1526  function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
1527      if ( ! isset( $term1->term_id ) ) {
1528          $term1 = get_term( $term1, $taxonomy );
1529      }
1530      if ( ! isset( $term2->parent ) ) {
1531          $term2 = get_term( $term2, $taxonomy );
1532      }
1533  
1534      if ( empty( $term1->term_id ) || empty( $term2->parent ) ) {
1535          return false;
1536      }
1537      if ( $term2->parent === $term1->term_id ) {
1538          return true;
1539      }
1540  
1541      return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
1542  }
1543  
1544  /**
1545   * Sanitize all term fields.
1546   *
1547   * Relies on sanitize_term_field() to sanitize the term. The difference is that
1548   * this function will sanitize **all** fields. The context is based
1549   * on sanitize_term_field().
1550   *
1551   * The `$term` is expected to be either an array or an object.
1552   *
1553   * @since 2.3.0
1554   *
1555   * @param array|object $term     The term to check.
1556   * @param string       $taxonomy The taxonomy name to use.
1557   * @param string       $context  Optional. Context in which to sanitize the term.
1558   *                               Accepts 'raw', 'edit', 'db', 'display', 'rss',
1559   *                               'attribute', or 'js'. Default 'display'.
1560   * @return array|object Term with all fields sanitized.
1561   */
1562  function sanitize_term( $term, $taxonomy, $context = 'display' ) {
1563      $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' );
1564  
1565      $do_object = is_object( $term );
1566  
1567      $term_id = $do_object ? $term->term_id : ( isset( $term['term_id'] ) ? $term['term_id'] : 0 );
1568  
1569      foreach ( (array) $fields as $field ) {
1570          if ( $do_object ) {
1571              if ( isset( $term->$field ) ) {
1572                  $term->$field = sanitize_term_field( $field, $term->$field, $term_id, $taxonomy, $context );
1573              }
1574          } else {
1575              if ( isset( $term[ $field ] ) ) {
1576                  $term[ $field ] = sanitize_term_field( $field, $term[ $field ], $term_id, $taxonomy, $context );
1577              }
1578          }
1579      }
1580  
1581      if ( $do_object ) {
1582          $term->filter = $context;
1583      } else {
1584          $term['filter'] = $context;
1585      }
1586  
1587      return $term;
1588  }
1589  
1590  /**
1591   * Cleanse the field value in the term based on the context.
1592   *
1593   * Passing a term field value through the function should be assumed to have
1594   * cleansed the value for whatever context the term field is going to be used.
1595   *
1596   * If no context or an unsupported context is given, then default filters will
1597   * be applied.
1598   *
1599   * There are enough filters for each context to support a custom filtering
1600   * without creating your own filter function. Simply create a function that
1601   * hooks into the filter you need.
1602   *
1603   * @since 2.3.0
1604   *
1605   * @param string $field    Term field to sanitize.
1606   * @param string $value    Search for this term value.
1607   * @param int    $term_id  Term ID.
1608   * @param string $taxonomy Taxonomy Name.
1609   * @param string $context  Context in which to sanitize the term field.
1610   *                         Accepts 'raw', 'edit', 'db', 'display', 'rss',
1611   *                         'attribute', or 'js'. Default 'display'.
1612   * @return mixed Sanitized field.
1613   */
1614  function sanitize_term_field( $field, $value, $term_id, $taxonomy, $context ) {
1615      $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' );
1616      if ( in_array( $field, $int_fields, true ) ) {
1617          $value = (int) $value;
1618          if ( $value < 0 ) {
1619              $value = 0;
1620          }
1621      }
1622  
1623      $context = strtolower( $context );
1624  
1625      if ( 'raw' === $context ) {
1626          return $value;
1627      }
1628  
1629      if ( 'edit' === $context ) {
1630  
1631          /**
1632           * Filters a term field to edit before it is sanitized.
1633           *
1634           * The dynamic portion of the filter name, `$field`, refers to the term field.
1635           *
1636           * @since 2.3.0
1637           *
1638           * @param mixed $value     Value of the term field.
1639           * @param int   $term_id   Term ID.
1640           * @param string $taxonomy Taxonomy slug.
1641           */
1642          $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy );
1643  
1644          /**
1645           * Filters the taxonomy field to edit before it is sanitized.
1646           *
1647           * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
1648           * to the taxonomy slug and taxonomy field, respectively.
1649           *
1650           * @since 2.3.0
1651           *
1652           * @param mixed $value   Value of the taxonomy field to edit.
1653           * @param int   $term_id Term ID.
1654           */
1655          $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id );
1656  
1657          if ( 'description' === $field ) {
1658              $value = esc_html( $value ); // textarea_escaped
1659          } else {
1660              $value = esc_attr( $value );
1661          }
1662      } elseif ( 'db' === $context ) {
1663  
1664          /**
1665           * Filters a term field value before it is sanitized.
1666           *
1667           * The dynamic portion of the filter name, `$field`, refers to the term field.
1668           *
1669           * @since 2.3.0
1670           *
1671           * @param mixed  $value    Value of the term field.
1672           * @param string $taxonomy Taxonomy slug.
1673           */
1674          $value = apply_filters( "pre_term_{$field}", $value, $taxonomy );
1675  
1676          /**
1677           * Filters a taxonomy field before it is sanitized.
1678           *
1679           * The dynamic portions of the filter name, `$taxonomy` and `$field`, refer
1680           * to the taxonomy slug and field name, respectively.
1681           *
1682           * @since 2.3.0
1683           *
1684           * @param mixed $value Value of the taxonomy field.
1685           */
1686          $value = apply_filters( "pre_{$taxonomy}_{$field}", $value );
1687  
1688          // Back compat filters.
1689          if ( 'slug' === $field ) {
1690              /**
1691               * Filters the category nicename before it is sanitized.
1692               *
1693               * Use the {@see 'pre_$taxonomy_$field'} hook instead.
1694               *
1695               * @since 2.0.3
1696               *
1697               * @param string $value The category nicename.
1698               */
1699              $value = apply_filters( 'pre_category_nicename', $value );
1700          }
1701      } elseif ( 'rss' === $context ) {
1702  
1703          /**
1704           * Filters the term field for use in RSS.
1705           *
1706           * The dynamic portion of the filter name, `$field`, refers to the term field.
1707           *
1708           * @since 2.3.0
1709           *
1710           * @param mixed  $value    Value of the term field.
1711           * @param string $taxonomy Taxonomy slug.
1712           */
1713          $value = apply_filters( "term_{$field}_rss", $value, $taxonomy );
1714  
1715          /**
1716           * Filters the taxonomy field for use in RSS.
1717           *
1718           * The dynamic portions of the hook name, `$taxonomy`, and `$field`, refer
1719           * to the taxonomy slug and field name, respectively.
1720           *
1721           * @since 2.3.0
1722           *
1723           * @param mixed $value Value of the taxonomy field.
1724           */
1725          $value = apply_filters( "{$taxonomy}_{$field}_rss", $value );
1726      } else {
1727          // Use display filters by default.
1728  
1729          /**
1730           * Filters the term field sanitized for display.
1731           *
1732           * The dynamic portion of the filter name, `$field`, refers to the term field name.
1733           *
1734           * @since 2.3.0
1735           *
1736           * @param mixed  $value    Value of the term field.
1737           * @param int    $term_id  Term ID.
1738           * @param string $taxonomy Taxonomy slug.
1739           * @param string $context  Context to retrieve the term field value.
1740           */
1741          $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context );
1742  
1743          /**
1744           * Filters the taxonomy field sanitized for display.
1745           *
1746           * The dynamic portions of the filter name, `$taxonomy`, and `$field`, refer
1747           * to the taxonomy slug and taxonomy field, respectively.
1748           *
1749           * @since 2.3.0
1750           *
1751           * @param mixed  $value   Value of the taxonomy field.
1752           * @param int    $term_id Term ID.
1753           * @param string $context Context to retrieve the taxonomy field value.
1754           */
1755          $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context );
1756      }
1757  
1758      if ( 'attribute' === $context ) {
1759          $value = esc_attr( $value );
1760      } elseif ( 'js' === $context ) {
1761          $value = esc_js( $value );
1762      }
1763      return $value;
1764  }
1765  
1766  /**
1767   * Count how many terms are in Taxonomy.
1768   *
1769   * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true).
1770   *
1771   * @since 2.3.0
1772   * @since 5.6.0 Changed the function signature so that the `$args` array can be provided as the first parameter.
1773   *
1774   * @internal The `$deprecated` parameter is parsed for backward compatibility only.
1775   *
1776   * @param array|string $args       Optional. Array of arguments that get passed to get_terms().
1777   *                                 Default empty array.
1778   * @param array|string $deprecated Optional. Argument array, when using the legacy function parameter format.
1779   *                                 If present, this parameter will be interpreted as `$args`, and the first
1780   *                                 function parameter will be parsed as a taxonomy or array of taxonomies.
1781   *                                 Default empty.
1782   * @return string|WP_Error Numeric string containing the number of terms in that
1783   *                         taxonomy or WP_Error if the taxonomy does not exist.
1784   */
1785  function wp_count_terms( $args = array(), $deprecated = '' ) {
1786      $use_legacy_args = false;
1787  
1788      // Check whether function is used with legacy signature: `$taxonomy` and `$args`.
1789      if ( $args
1790          && ( is_string( $args ) && taxonomy_exists( $args )
1791              || is_array( $args ) && wp_is_numeric_array( $args ) )
1792      ) {
1793          $use_legacy_args = true;
1794      }
1795  
1796      $defaults = array( 'hide_empty' => false );
1797  
1798      if ( $use_legacy_args ) {
1799          $defaults['taxonomy'] = $args;
1800          $args                 = $deprecated;
1801      }
1802  
1803      $args = wp_parse_args( $args, $defaults );
1804  
1805      // Backward compatibility.
1806      if ( isset( $args['ignore_empty'] ) ) {
1807          $args['hide_empty'] = $args['ignore_empty'];
1808          unset( $args['ignore_empty'] );
1809      }
1810  
1811      $args['fields'] = 'count';
1812  
1813      return get_terms( $args );
1814  }
1815  
1816  /**
1817   * Will unlink the object from the taxonomy or taxonomies.
1818   *
1819   * Will remove all relationships between the object and any terms in
1820   * a particular taxonomy or taxonomies. Does not remove the term or
1821   * taxonomy itself.
1822   *
1823   * @since 2.3.0
1824   *
1825   * @param int          $object_id  The term Object Id that refers to the term.
1826   * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name.
1827   */
1828  function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
1829      $object_id = (int) $object_id;
1830  
1831      if ( ! is_array( $taxonomies ) ) {
1832          $taxonomies = array( $taxonomies );
1833      }
1834  
1835      foreach ( (array) $taxonomies as $taxonomy ) {
1836          $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
1837          $term_ids = array_map( 'intval', $term_ids );
1838          wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
1839      }
1840  }
1841  
1842  /**
1843   * Removes a term from the database.
1844   *
1845   * If the term is a parent of other terms, then the children will be updated to
1846   * that term's parent.
1847   *
1848   * Metadata associated with the term will be deleted.
1849   *
1850   * @since 2.3.0
1851   *
1852   * @global wpdb $wpdb WordPress database abstraction object.
1853   *
1854   * @param int          $term     Term ID.
1855   * @param string       $taxonomy Taxonomy Name.
1856   * @param array|string $args {
1857   *     Optional. Array of arguments to override the default term ID. Default empty array.
1858   *
1859   *     @type int  $default       The term ID to make the default term. This will only override
1860   *                               the terms found if there is only one term found. Any other and
1861   *                               the found terms are used.
1862   *     @type bool $force_default Optional. Whether to force the supplied term as default to be
1863   *                               assigned even if the object was not going to be term-less.
1864   *                               Default false.
1865   * }
1866   * @return bool|int|WP_Error True on success, false if term does not exist. Zero on attempted
1867   *                           deletion of default Category. WP_Error if the taxonomy does not exist.
1868   */
1869  function wp_delete_term( $term, $taxonomy, $args = array() ) {
1870      global $wpdb;
1871  
1872      $term = (int) $term;
1873  
1874      $ids = term_exists( $term, $taxonomy );
1875      if ( ! $ids ) {
1876          return false;
1877      }
1878      if ( is_wp_error( $ids ) ) {
1879          return $ids;
1880      }
1881  
1882      $tt_id = $ids['term_taxonomy_id'];
1883  
1884      $defaults = array();
1885  
1886      if ( 'category' === $taxonomy ) {
1887          $defaults['default'] = (int) get_option( 'default_category' );
1888          if ( $defaults['default'] === $term ) {
1889              return 0; // Don't delete the default category.
1890          }
1891      }
1892  
1893      // Don't delete the default custom taxonomy term.
1894      $taxonomy_object = get_taxonomy( $taxonomy );
1895      if ( ! empty( $taxonomy_object->default_term ) ) {
1896          $defaults['default'] = (int) get_option( 'default_term_' . $taxonomy );
1897          if ( $defaults['default'] === $term ) {
1898              return 0;
1899          }
1900      }
1901  
1902      $args = wp_parse_args( $args, $defaults );
1903  
1904      if ( isset( $args['default'] ) ) {
1905          $default = (int) $args['default'];
1906          if ( ! term_exists( $default, $taxonomy ) ) {
1907              unset( $default );
1908          }
1909      }
1910  
1911      if ( isset( $args['force_default'] ) ) {
1912          $force_default = $args['force_default'];
1913      }
1914  
1915      /**
1916       * Fires when deleting a term, before any modifications are made to posts or terms.
1917       *
1918       * @since 4.1.0
1919       *
1920       * @param int    $term     Term ID.
1921       * @param string $taxonomy Taxonomy Name.
1922       */
1923      do_action( 'pre_delete_term', $term, $taxonomy );
1924  
1925      // Update children to point to new parent.
1926      if ( is_taxonomy_hierarchical( $taxonomy ) ) {
1927          $term_obj = get_term( $term, $taxonomy );
1928          if ( is_wp_error( $term_obj ) ) {
1929              return $term_obj;
1930          }
1931          $parent = $term_obj->parent;
1932  
1933          $edit_ids    = $wpdb->get_results( "SELECT term_id, term_taxonomy_id FROM $wpdb->term_taxonomy WHERE `parent` = " . (int) $term_obj->term_id );
1934          $edit_tt_ids = wp_list_pluck( $edit_ids, 'term_taxonomy_id' );
1935  
1936          /**
1937           * Fires immediately before a term to delete's children are reassigned a parent.
1938           *
1939           * @since 2.9.0
1940           *
1941           * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
1942           */
1943          do_action( 'edit_term_taxonomies', $edit_tt_ids );
1944  
1945          $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id ) + compact( 'taxonomy' ) );
1946  
1947          // Clean the cache for all child terms.
1948          $edit_term_ids = wp_list_pluck( $edit_ids, 'term_id' );
1949          clean_term_cache( $edit_term_ids, $taxonomy );
1950  
1951          /**
1952           * Fires immediately after a term to delete's children are reassigned a parent.
1953           *
1954           * @since 2.9.0
1955           *
1956           * @param array $edit_tt_ids An array of term taxonomy IDs for the given term.
1957           */
1958          do_action( 'edited_term_taxonomies', $edit_tt_ids );
1959      }
1960  
1961      // Get the term before deleting it or its term relationships so we can pass to actions below.
1962      $deleted_term = get_term( $term, $taxonomy );
1963  
1964      $object_ids = (array) $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
1965  
1966      foreach ( $object_ids as $object_id ) {
1967          if ( ! isset( $default ) ) {
1968              wp_remove_object_terms( $object_id, $term, $taxonomy );
1969              continue;
1970          }
1971  
1972          $terms = wp_get_object_terms(
1973              $object_id,
1974              $taxonomy,
1975              array(
1976                  'fields'  => 'ids',
1977                  'orderby' => 'none',
1978              )
1979          );
1980  
1981          if ( 1 === count( $terms ) && isset( $default ) ) {
1982              $terms = array( $default );
1983          } else {
1984              $terms = array_diff( $terms, array( $term ) );
1985              if ( isset( $default ) && isset( $force_default ) && $force_default ) {
1986                  $terms = array_merge( $terms, array( $default ) );
1987              }
1988          }
1989  
1990          $terms = array_map( 'intval', $terms );
1991          wp_set_object_terms( $object_id, $terms, $taxonomy );
1992      }
1993  
1994      // Clean the relationship caches for all object types using this term.
1995      $tax_object = get_taxonomy( $taxonomy );
1996      foreach ( $tax_object->object_type as $object_type ) {
1997          clean_object_term_cache( $object_ids, $object_type );
1998      }
1999  
2000      $term_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->termmeta WHERE term_id = %d ", $term ) );
2001      foreach ( $term_meta_ids as $mid ) {
2002          delete_metadata_by_mid( 'term', $mid );
2003      }
2004  
2005      /**
2006       * Fires immediately before a term taxonomy ID is deleted.
2007       *
2008       * @since 2.9.0
2009       *
2010       * @param int $tt_id Term taxonomy ID.
2011       */
2012      do_action( 'delete_term_taxonomy', $tt_id );
2013  
2014      $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2015  
2016      /**
2017       * Fires immediately after a term taxonomy ID is deleted.
2018       *
2019       * @since 2.9.0
2020       *
2021       * @param int $tt_id Term taxonomy ID.
2022       */
2023      do_action( 'deleted_term_taxonomy', $tt_id );
2024  
2025      // Delete the term if no taxonomies use it.
2026      if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term ) ) ) {
2027          $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) );
2028      }
2029  
2030      clean_term_cache( $term, $taxonomy );
2031  
2032      /**
2033       * Fires after a term is deleted from the database and the cache is cleaned.
2034       *
2035       * The {@see 'delete_$taxonomy'} hook is also available for targeting a specific
2036       * taxonomy.
2037       *
2038       * @since 2.5.0
2039       * @since 4.5.0 Introduced the `$object_ids` argument.
2040       *
2041       * @param int     $term         Term ID.
2042       * @param int     $tt_id        Term taxonomy ID.
2043       * @param string  $taxonomy     Taxonomy slug.
2044       * @param WP_Term $deleted_term Copy of the already-deleted term.
2045       * @param array   $object_ids   List of term object IDs.
2046       */
2047      do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term, $object_ids );
2048  
2049      /**
2050       * Fires after a term in a specific taxonomy is deleted.
2051       *
2052       * The dynamic portion of the hook name, `$taxonomy`, refers to the specific
2053       * taxonomy the term belonged to.
2054       *
2055       * Possible hook names include:
2056       *
2057       *  - `delete_category`
2058       *  - `delete_post_tag`
2059       *
2060       * @since 2.3.0
2061       * @since 4.5.0 Introduced the `$object_ids` argument.
2062       *
2063       * @param int     $term         Term ID.
2064       * @param int     $tt_id        Term taxonomy ID.
2065       * @param WP_Term $deleted_term Copy of the already-deleted term.
2066       * @param array   $object_ids   List of term object IDs.
2067       */
2068      do_action( "delete_{$taxonomy}", $term, $tt_id, $deleted_term, $object_ids );
2069  
2070      return true;
2071  }
2072  
2073  /**
2074   * Deletes one existing category.
2075   *
2076   * @since 2.0.0
2077   *
2078   * @param int $cat_ID Category term ID.
2079   * @return bool|int|WP_Error Returns true if completes delete action; false if term doesn't exist;
2080   *  Zero on attempted deletion of default Category; WP_Error object is also a possibility.
2081   */
2082  function wp_delete_category( $cat_ID ) {
2083      return wp_delete_term( $cat_ID, 'category' );
2084  }
2085  
2086  /**
2087   * Retrieves the terms associated with the given object(s), in the supplied taxonomies.
2088   *
2089   * @since 2.3.0
2090   * @since 4.2.0 Added support for 'taxonomy', 'parent', and 'term_taxonomy_id' values of `$orderby`.
2091   *              Introduced `$parent` argument.
2092   * @since 4.4.0 Introduced `$meta_query` and `$update_term_meta_cache` arguments. When `$fields` is 'all' or
2093   *              'all_with_object_id', an array of `WP_Term` objects will be returned.
2094   * @since 4.7.0 Refactored to use WP_Term_Query, and to support any WP_Term_Query arguments.
2095   *
2096   * @param int|int[]       $object_ids The ID(s) of the object(s) to retrieve.
2097   * @param string|string[] $taxonomies The taxonomy names to retrieve terms from.
2098   * @param array|string    $args       See WP_Term_Query::__construct() for supported arguments.
2099   * @return WP_Term[]|WP_Error Array of terms or empty array if no terms found.
2100   *                            WP_Error if any of the taxonomies don't exist.
2101   */
2102  function wp_get_object_terms( $object_ids, $taxonomies, $args = array() ) {
2103      if ( empty( $object_ids ) || empty( $taxonomies ) ) {
2104          return array();
2105      }
2106  
2107      if ( ! is_array( $taxonomies ) ) {
2108          $taxonomies = array( $taxonomies );
2109      }
2110  
2111      foreach ( $taxonomies as $taxonomy ) {
2112          if ( ! taxonomy_exists( $taxonomy ) ) {
2113              return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2114          }
2115      }
2116  
2117      if ( ! is_array( $object_ids ) ) {
2118          $object_ids = array( $object_ids );
2119      }
2120      $object_ids = array_map( 'intval', $object_ids );
2121  
2122      $args = wp_parse_args( $args );
2123  
2124      /**
2125       * Filters arguments for retrieving object terms.
2126       *
2127       * @since 4.9.0
2128       *
2129       * @param array    $args       An array of arguments for retrieving terms for the given object(s).
2130       *                             See {@see wp_get_object_terms()} for details.
2131       * @param int[]    $object_ids Array of object IDs.
2132       * @param string[] $taxonomies Array of taxonomy names to retrieve terms from.
2133       */
2134      $args = apply_filters( 'wp_get_object_terms_args', $args, $object_ids, $taxonomies );
2135  
2136      /*
2137       * When one or more queried taxonomies is registered with an 'args' array,
2138       * those params override the `$args` passed to this function.
2139       */
2140      $terms = array();
2141      if ( count( $taxonomies ) > 1 ) {
2142          foreach ( $taxonomies as $index => $taxonomy ) {
2143              $t = get_taxonomy( $taxonomy );
2144              if ( isset( $t->args ) && is_array( $t->args ) && array_merge( $args, $t->args ) != $args ) {
2145                  unset( $taxonomies[ $index ] );
2146                  $terms = array_merge( $terms, wp_get_object_terms( $object_ids, $taxonomy, array_merge( $args, $t->args ) ) );
2147              }
2148          }
2149      } else {
2150          $t = get_taxonomy( $taxonomies[0] );
2151          if ( isset( $t->args ) && is_array( $t->args ) ) {
2152              $args = array_merge( $args, $t->args );
2153          }
2154      }
2155  
2156      $args['taxonomy']   = $taxonomies;
2157      $args['object_ids'] = $object_ids;
2158  
2159      // Taxonomies registered without an 'args' param are handled here.
2160      if ( ! empty( $taxonomies ) ) {
2161          $terms_from_remaining_taxonomies = get_terms( $args );
2162  
2163          // Array keys should be preserved for values of $fields that use term_id for keys.
2164          if ( ! empty( $args['fields'] ) && 0 === strpos( $args['fields'], 'id=>' ) ) {
2165              $terms = $terms + $terms_from_remaining_taxonomies;
2166          } else {
2167              $terms = array_merge( $terms, $terms_from_remaining_taxonomies );
2168          }
2169      }
2170  
2171      /**
2172       * Filters the terms for a given object or objects.
2173       *
2174       * @since 4.2.0
2175       *
2176       * @param WP_Term[] $terms      Array of terms for the given object or objects.
2177       * @param int[]     $object_ids Array of object IDs for which terms were retrieved.
2178       * @param string[]  $taxonomies Array of taxonomy names from which terms were retrieved.
2179       * @param array     $args       Array of arguments for retrieving terms for the given
2180       *                              object(s). See wp_get_object_terms() for details.
2181       */
2182      $terms = apply_filters( 'get_object_terms', $terms, $object_ids, $taxonomies, $args );
2183  
2184      $object_ids = implode( ',', $object_ids );
2185      $taxonomies = "'" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "'";
2186  
2187      /**
2188       * Filters the terms for a given object or objects.
2189       *
2190       * The `$taxonomies` parameter passed to this filter is formatted as a SQL fragment. The
2191       * {@see 'get_object_terms'} filter is recommended as an alternative.
2192       *
2193       * @since 2.8.0
2194       *
2195       * @param WP_Term[] $terms      Array of terms for the given object or objects.
2196       * @param string    $object_ids Comma separated list of object IDs for which terms were retrieved.
2197       * @param string    $taxonomies SQL fragment of taxonomy names from which terms were retrieved.
2198       * @param array     $args       Array of arguments for retrieving terms for the given
2199       *                              object(s). See wp_get_object_terms() for details.
2200       */
2201      return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args );
2202  }
2203  
2204  /**
2205   * Add a new term to the database.
2206   *
2207   * A non-existent term is inserted in the following sequence:
2208   * 1. The term is added to the term table, then related to the taxonomy.
2209   * 2. If everything is correct, several actions are fired.
2210   * 3. The 'term_id_filter' is evaluated.
2211   * 4. The term cache is cleaned.
2212   * 5. Several more actions are fired.
2213   * 6. An array is returned containing the `term_id` and `term_taxonomy_id`.
2214   *
2215   * If the 'slug' argument is not empty, then it is checked to see if the term
2216   * is invalid. If it is not a valid, existing term, it is added and the term_id
2217   * is given.
2218   *
2219   * If the taxonomy is hierarchical, and the 'parent' argument is not empty,
2220   * the term is inserted and the term_id will be given.
2221   *
2222   * Error handling:
2223   * If `$taxonomy` does not exist or `$term` is empty,
2224   * a WP_Error object will be returned.
2225   *
2226   * If the term already exists on the same hierarchical level,
2227   * or the term slug and name are not unique, a WP_Error object will be returned.
2228   *
2229   * @global wpdb $wpdb WordPress database abstraction object.
2230   *
2231   * @since 2.3.0
2232   *
2233   * @param string       $term     The term name to add.
2234   * @param string       $taxonomy The taxonomy to which to add the term.
2235   * @param array|string $args {
2236   *     Optional. Array or query string of arguments for inserting a term.
2237   *
2238   *     @type string $alias_of    Slug of the term to make this term an alias of.
2239   *                               Default empty string. Accepts a term slug.
2240   *     @type string $description The term description. Default empty string.
2241   *     @type int    $parent      The id of the parent term. Default 0.
2242   *     @type string $slug        The term slug to use. Default empty string.
2243   * }
2244   * @return array|WP_Error {
2245   *     An array of the new term data, WP_Error otherwise.
2246   *
2247   *     @type int        $term_id          The new term ID.
2248   *     @type int|string $term_taxonomy_id The new term taxonomy ID. Can be a numeric string.
2249   * }
2250   */
2251  function wp_insert_term( $term, $taxonomy, $args = array() ) {
2252      global $wpdb;
2253  
2254      if ( ! taxonomy_exists( $taxonomy ) ) {
2255          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2256      }
2257  
2258      /**
2259       * Filters a term before it is sanitized and inserted into the database.
2260       *
2261       * @since 3.0.0
2262       *
2263       * @param string|WP_Error $term     The term name to add, or a WP_Error object if there's an error.
2264       * @param string          $taxonomy Taxonomy slug.
2265       */
2266      $term = apply_filters( 'pre_insert_term', $term, $taxonomy );
2267  
2268      if ( is_wp_error( $term ) ) {
2269          return $term;
2270      }
2271  
2272      if ( is_int( $term ) && 0 === $term ) {
2273          return new WP_Error( 'invalid_term_id', __( 'Invalid term ID.' ) );
2274      }
2275  
2276      if ( '' === trim( $term ) ) {
2277          return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
2278      }
2279  
2280      $defaults = array(
2281          'alias_of'    => '',
2282          'description' => '',
2283          'parent'      => 0,
2284          'slug'        => '',
2285      );
2286      $args     = wp_parse_args( $args, $defaults );
2287  
2288      if ( (int) $args['parent'] > 0 && ! term_exists( (int) $args['parent'] ) ) {
2289          return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
2290      }
2291  
2292      $args['name']     = $term;
2293      $args['taxonomy'] = $taxonomy;
2294  
2295      // Coerce null description to strings, to avoid database errors.
2296      $args['description'] = (string) $args['description'];
2297  
2298      $args = sanitize_term( $args, $taxonomy, 'db' );
2299  
2300      // expected_slashed ($name)
2301      $name        = wp_unslash( $args['name'] );
2302      $description = wp_unslash( $args['description'] );
2303      $parent      = (int) $args['parent'];
2304  
2305      $slug_provided = ! empty( $args['slug'] );
2306      if ( ! $slug_provided ) {
2307          $slug = sanitize_title( $name );
2308      } else {
2309          $slug = $args['slug'];
2310      }
2311  
2312      $term_group = 0;
2313      if ( $args['alias_of'] ) {
2314          $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
2315          if ( ! empty( $alias->term_group ) ) {
2316              // The alias we want is already in a group, so let's use that one.
2317              $term_group = $alias->term_group;
2318          } elseif ( ! empty( $alias->term_id ) ) {
2319              /*
2320               * The alias is not in a group, so we create a new one
2321               * and add the alias to it.
2322               */
2323              $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1;
2324  
2325              wp_update_term(
2326                  $alias->term_id,
2327                  $taxonomy,
2328                  array(
2329                      'term_group' => $term_group,
2330                  )
2331              );
2332          }
2333      }
2334  
2335      /*
2336       * Prevent the creation of terms with duplicate names at the same level of a taxonomy hierarchy,
2337       * unless a unique slug has been explicitly provided.
2338       */
2339      $name_matches = get_terms(
2340          array(
2341              'taxonomy'               => $taxonomy,
2342              'name'                   => $name,
2343              'hide_empty'             => false,
2344              'parent'                 => $args['parent'],
2345              'update_term_meta_cache' => false,
2346          )
2347      );
2348  
2349      /*
2350       * The `name` match in `get_terms()` doesn't differentiate accented characters,
2351       * so we do a stricter comparison here.
2352       */
2353      $name_match = null;
2354      if ( $name_matches ) {
2355          foreach ( $name_matches as $_match ) {
2356              if ( strtolower( $name ) === strtolower( $_match->name ) ) {
2357                  $name_match = $_match;
2358                  break;
2359              }
2360          }
2361      }
2362  
2363      if ( $name_match ) {
2364          $slug_match = get_term_by( 'slug', $slug, $taxonomy );
2365          if ( ! $slug_provided || $name_match->slug === $slug || $slug_match ) {
2366              if ( is_taxonomy_hierarchical( $taxonomy ) ) {
2367                  $siblings = get_terms(
2368                      array(
2369                          'taxonomy'               => $taxonomy,
2370                          'get'                    => 'all',
2371                          'parent'                 => $parent,
2372                          'update_term_meta_cache' => false,
2373                      )
2374                  );
2375  
2376                  $existing_term = null;
2377                  $sibling_names = wp_list_pluck( $siblings, 'name' );
2378                  $sibling_slugs = wp_list_pluck( $siblings, 'slug' );
2379  
2380                  if ( ( ! $slug_provided || $name_match->slug === $slug ) && in_array( $name, $sibling_names, true ) ) {
2381                      $existing_term = $name_match;
2382                  } elseif ( $slug_match && in_array( $slug, $sibling_slugs, true ) ) {
2383                      $existing_term = $slug_match;
2384                  }
2385  
2386                  if ( $existing_term ) {
2387                      return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $existing_term->term_id );
2388                  }
2389              } else {
2390                  return new WP_Error( 'term_exists', __( 'A term with the name provided already exists in this taxonomy.' ), $name_match->term_id );
2391              }
2392          }
2393      }
2394  
2395      $slug = wp_unique_term_slug( $slug, (object) $args );
2396  
2397      $data = compact( 'name', 'slug', 'term_group' );
2398  
2399      /**
2400       * Filters term data before it is inserted into the database.
2401       *
2402       * @since 4.7.0
2403       *
2404       * @param array  $data     Term data to be inserted.
2405       * @param string $taxonomy Taxonomy slug.
2406       * @param array  $args     Arguments passed to wp_insert_term().
2407       */
2408      $data = apply_filters( 'wp_insert_term_data', $data, $taxonomy, $args );
2409  
2410      if ( false === $wpdb->insert( $wpdb->terms, $data ) ) {
2411          return new WP_Error( 'db_insert_error', __( 'Could not insert term into the database.' ), $wpdb->last_error );
2412      }
2413  
2414      $term_id = (int) $wpdb->insert_id;
2415  
2416      // Seems unreachable. However, is used in the case that a term name is provided, which sanitizes to an empty string.
2417      if ( empty( $slug ) ) {
2418          $slug = sanitize_title( $slug, $term_id );
2419  
2420          /** This action is documented in wp-includes/taxonomy.php */
2421          do_action( 'edit_terms', $term_id, $taxonomy );
2422          $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
2423  
2424          /** This action is documented in wp-includes/taxonomy.php */
2425          do_action( 'edited_terms', $term_id, $taxonomy );
2426      }
2427  
2428      $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
2429  
2430      if ( ! empty( $tt_id ) ) {
2431          return array(
2432              'term_id'          => $term_id,
2433              'term_taxonomy_id' => $tt_id,
2434          );
2435      }
2436  
2437      if ( false === $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ) + array( 'count' => 0 ) ) ) {
2438          return new WP_Error( 'db_insert_error', __( 'Could not insert term taxonomy into the database.' ), $wpdb->last_error );
2439      }
2440  
2441      $tt_id = (int) $wpdb->insert_id;
2442  
2443      /*
2444       * Sanity check: if we just created a term with the same parent + taxonomy + slug but a higher term_id than
2445       * an existing term, then we have unwittingly created a duplicate term. Delete the dupe, and use the term_id
2446       * and term_taxonomy_id of the older term instead. Then return out of the function so that the "create" hooks
2447       * are not fired.
2448       */
2449      $duplicate_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.term_id, t.slug, tt.term_taxonomy_id, tt.taxonomy FROM $wpdb->terms t INNER JOIN $wpdb->term_taxonomy tt ON ( tt.term_id = t.term_id ) WHERE t.slug = %s AND tt.parent = %d AND tt.taxonomy = %s AND t.term_id < %d AND tt.term_taxonomy_id != %d", $slug, $parent, $taxonomy, $term_id, $tt_id ) );
2450  
2451      /**
2452       * Filters the duplicate term check that takes place during term creation.
2453       *
2454       * Term parent+taxonomy+slug combinations are meant to be unique, and wp_insert_term()
2455       * performs a last-minute confirmation of this uniqueness before allowing a new term
2456       * to be created. Plugins with different uniqueness requirements may use this filter
2457       * to bypass or modify the duplicate-term check.
2458       *
2459       * @since 5.1.0
2460       *
2461       * @param object $duplicate_term Duplicate term row from terms table, if found.
2462       * @param string $term           Term being inserted.
2463       * @param string $taxonomy       Taxonomy name.
2464       * @param array  $args           Term arguments passed to the function.
2465       * @param int    $tt_id          term_taxonomy_id for the newly created term.
2466       */
2467      $duplicate_term = apply_filters( 'wp_insert_term_duplicate_term_check', $duplicate_term, $term, $taxonomy, $args, $tt_id );
2468  
2469      if ( $duplicate_term ) {
2470          $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) );
2471          $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) );
2472  
2473          $term_id = (int) $duplicate_term->term_id;
2474          $tt_id   = (int) $duplicate_term->term_taxonomy_id;
2475  
2476          clean_term_cache( $term_id, $taxonomy );
2477          return array(
2478              'term_id'          => $term_id,
2479              'term_taxonomy_id' => $tt_id,
2480          );
2481      }
2482  
2483      /**
2484       * Fires immediately after a new term is created, before the term cache is cleaned.
2485       *
2486       * The {@see 'create_$taxonomy'} hook is also available for targeting a specific
2487       * taxonomy.
2488       *
2489       * @since 2.3.0
2490       *
2491       * @param int    $term_id  Term ID.
2492       * @param int    $tt_id    Term taxonomy ID.
2493       * @param string $taxonomy Taxonomy slug.
2494       */
2495      do_action( 'create_term', $term_id, $tt_id, $taxonomy );
2496  
2497      /**
2498       * Fires after a new term is created for a specific taxonomy.
2499       *
2500       * The dynamic portion of the hook name, `$taxonomy`, refers
2501       * to the slug of the taxonomy the term was created for.
2502       *
2503       * Possible hook names include:
2504       *
2505       *  - `create_category`
2506       *  - `create_post_tag`
2507       *
2508       * @since 2.3.0
2509       *
2510       * @param int $term_id Term ID.
2511       * @param int $tt_id   Term taxonomy ID.
2512       */
2513      do_action( "create_{$taxonomy}", $term_id, $tt_id );
2514  
2515      /**
2516       * Filters the term ID after a new term is created.
2517       *
2518       * @since 2.3.0
2519       *
2520       * @param int $term_id Term ID.
2521       * @param int $tt_id   Term taxonomy ID.
2522       */
2523      $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
2524  
2525      clean_term_cache( $term_id, $taxonomy );
2526  
2527      /**
2528       * Fires after a new term is created, and after the term cache has been cleaned.
2529       *
2530       * The {@see 'created_$taxonomy'} hook is also available for targeting a specific
2531       * taxonomy.
2532       *
2533       * @since 2.3.0
2534       *
2535       * @param int    $term_id  Term ID.
2536       * @param int    $tt_id    Term taxonomy ID.
2537       * @param string $taxonomy Taxonomy slug.
2538       */
2539      do_action( 'created_term', $term_id, $tt_id, $taxonomy );
2540  
2541      /**
2542       * Fires after a new term in a specific taxonomy is created, and after the term
2543       * cache has been cleaned.
2544       *
2545       * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2546       *
2547       * Possible hook names include:
2548       *
2549       *  - `created_category`
2550       *  - `created_post_tag`
2551       *
2552       * @since 2.3.0
2553       *
2554       * @param int $term_id Term ID.
2555       * @param int $tt_id   Term taxonomy ID.
2556       */
2557      do_action( "created_{$taxonomy}", $term_id, $tt_id );
2558  
2559      /**
2560       * Fires after a term has been saved, and the term cache has been cleared.
2561       *
2562       * The {@see 'saved_$taxonomy'} hook is also available for targeting a specific
2563       * taxonomy.
2564       *
2565       * @since 5.5.0
2566       *
2567       * @param int    $term_id  Term ID.
2568       * @param int    $tt_id    Term taxonomy ID.
2569       * @param string $taxonomy Taxonomy slug.
2570       * @param bool   $update   Whether this is an existing term being updated.
2571       */
2572      do_action( 'saved_term', $term_id, $tt_id, $taxonomy, false );
2573  
2574      /**
2575       * Fires after a term in a specific taxonomy has been saved, and the term
2576       * cache has been cleared.
2577       *
2578       * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
2579       *
2580       * Possible hook names include:
2581       *
2582       *  - `saved_category`
2583       *  - `saved_post_tag`
2584       *
2585       * @since 5.5.0
2586       *
2587       * @param int  $term_id Term ID.
2588       * @param int  $tt_id   Term taxonomy ID.
2589       * @param bool $update  Whether this is an existing term being updated.
2590       */
2591      do_action( "saved_{$taxonomy}", $term_id, $tt_id, false );
2592  
2593      return array(
2594          'term_id'          => $term_id,
2595          'term_taxonomy_id' => $tt_id,
2596      );
2597  }
2598  
2599  /**
2600   * Create Term and Taxonomy Relationships.
2601   *
2602   * Relates an object (post, link etc) to a term and taxonomy type. Creates the
2603   * term and taxonomy relationship if it doesn't already exist. Creates a term if
2604   * it doesn't exist (using the slug).
2605   *
2606   * A relationship means that the term is grouped in or belongs to the taxonomy.
2607   * A term has no meaning until it is given context by defining which taxonomy it
2608   * exists under.
2609   *
2610   * @since 2.3.0
2611   *
2612   * @global wpdb $wpdb WordPress database abstraction object.
2613   *
2614   * @param int              $object_id The object to relate to.
2615   * @param string|int|array $terms     A single term slug, single term ID, or array of either term slugs or IDs.
2616   *                                    Will replace all existing related terms in this taxonomy. Passing an
2617   *                                    empty value will remove all related terms.
2618   * @param string           $taxonomy  The context in which to relate the term to the object.
2619   * @param bool             $append    Optional. If false will delete difference of terms. Default false.
2620   * @return array|WP_Error Term taxonomy IDs of the affected terms or WP_Error on failure.
2621   */
2622  function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) {
2623      global $wpdb;
2624  
2625      $object_id = (int) $object_id;
2626  
2627      if ( ! taxonomy_exists( $taxonomy ) ) {
2628          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2629      }
2630  
2631      if ( ! is_array( $terms ) ) {
2632          $terms = array( $terms );
2633      }
2634  
2635      if ( ! $append ) {
2636          $old_tt_ids = wp_get_object_terms(
2637              $object_id,
2638              $taxonomy,
2639              array(
2640                  'fields'                 => 'tt_ids',
2641                  'orderby'                => 'none',
2642                  'update_term_meta_cache' => false,
2643              )
2644          );
2645      } else {
2646          $old_tt_ids = array();
2647      }
2648  
2649      $tt_ids     = array();
2650      $term_ids   = array();
2651      $new_tt_ids = array();
2652  
2653      foreach ( (array) $terms as $term ) {
2654          if ( '' === trim( $term ) ) {
2655              continue;
2656          }
2657  
2658          $term_info = term_exists( $term, $taxonomy );
2659  
2660          if ( ! $term_info ) {
2661              // Skip if a non-existent term ID is passed.
2662              if ( is_int( $term ) ) {
2663                  continue;
2664              }
2665  
2666              $term_info = wp_insert_term( $term, $taxonomy );
2667          }
2668  
2669          if ( is_wp_error( $term_info ) ) {
2670              return $term_info;
2671          }
2672  
2673          $term_ids[] = $term_info['term_id'];
2674          $tt_id      = $term_info['term_taxonomy_id'];
2675          $tt_ids[]   = $tt_id;
2676  
2677          if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) ) {
2678              continue;
2679          }
2680  
2681          /**
2682           * Fires immediately before an object-term relationship is added.
2683           *
2684           * @since 2.9.0
2685           * @since 4.7.0 Added the `$taxonomy` parameter.
2686           *
2687           * @param int    $object_id Object ID.
2688           * @param int    $tt_id     Term taxonomy ID.
2689           * @param string $taxonomy  Taxonomy slug.
2690           */
2691          do_action( 'add_term_relationship', $object_id, $tt_id, $taxonomy );
2692  
2693          $wpdb->insert(
2694              $wpdb->term_relationships,
2695              array(
2696                  'object_id'        => $object_id,
2697                  'term_taxonomy_id' => $tt_id,
2698              )
2699          );
2700  
2701          /**
2702           * Fires immediately after an object-term relationship is added.
2703           *
2704           * @since 2.9.0
2705           * @since 4.7.0 Added the `$taxonomy` parameter.
2706           *
2707           * @param int    $object_id Object ID.
2708           * @param int    $tt_id     Term taxonomy ID.
2709           * @param string $taxonomy  Taxonomy slug.
2710           */
2711          do_action( 'added_term_relationship', $object_id, $tt_id, $taxonomy );
2712  
2713          $new_tt_ids[] = $tt_id;
2714      }
2715  
2716      if ( $new_tt_ids ) {
2717          wp_update_term_count( $new_tt_ids, $taxonomy );
2718      }
2719  
2720      if ( ! $append ) {
2721          $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids );
2722  
2723          if ( $delete_tt_ids ) {
2724              $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'";
2725              $delete_term_ids  = $wpdb->get_col( $wpdb->prepare( "SELECT tt.term_id FROM $wpdb->term_taxonomy AS tt WHERE tt.taxonomy = %s AND tt.term_taxonomy_id IN ($in_delete_tt_ids)", $taxonomy ) );
2726              $delete_term_ids  = array_map( 'intval', $delete_term_ids );
2727  
2728              $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy );
2729              if ( is_wp_error( $remove ) ) {
2730                  return $remove;
2731              }
2732          }
2733      }
2734  
2735      $t = get_taxonomy( $taxonomy );
2736  
2737      if ( ! $append && isset( $t->sort ) && $t->sort ) {
2738          $values     = array();
2739          $term_order = 0;
2740  
2741          $final_tt_ids = wp_get_object_terms(
2742              $object_id,
2743              $taxonomy,
2744              array(
2745                  'fields'                 => 'tt_ids',
2746                  'update_term_meta_cache' => false,
2747              )
2748          );
2749  
2750          foreach ( $tt_ids as $tt_id ) {
2751              if ( in_array( (int) $tt_id, $final_tt_ids, true ) ) {
2752                  $values[] = $wpdb->prepare( '(%d, %d, %d)', $object_id, $tt_id, ++$term_order );
2753              }
2754          }
2755  
2756          if ( $values ) {
2757              if ( false === $wpdb->query( "INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . implode( ',', $values ) . ' ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)' ) ) {
2758                  return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database.' ), $wpdb->last_error );
2759              }
2760          }
2761      }
2762  
2763      wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2764      wp_cache_delete( 'last_changed', 'terms' );
2765  
2766      /**
2767       * Fires after an object's terms have been set.
2768       *
2769       * @since 2.8.0
2770       *
2771       * @param int    $object_id  Object ID.
2772       * @param array  $terms      An array of object term IDs or slugs.
2773       * @param array  $tt_ids     An array of term taxonomy IDs.
2774       * @param string $taxonomy   Taxonomy slug.
2775       * @param bool   $append     Whether to append new terms to the old terms.
2776       * @param array  $old_tt_ids Old array of term taxonomy IDs.
2777       */
2778      do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids );
2779  
2780      return $tt_ids;
2781  }
2782  
2783  /**
2784   * Add term(s) associated with a given object.
2785   *
2786   * @since 3.6.0
2787   *
2788   * @param int              $object_id The ID of the object to which the terms will be added.
2789   * @param string|int|array $terms     The slug(s) or ID(s) of the term(s) to add.
2790   * @param array|string     $taxonomy  Taxonomy name.
2791   * @return array|WP_Error Term taxonomy IDs of the affected terms.
2792   */
2793  function wp_add_object_terms( $object_id, $terms, $taxonomy ) {
2794      return wp_set_object_terms( $object_id, $terms, $taxonomy, true );
2795  }
2796  
2797  /**
2798   * Remove term(s) associated with a given object.
2799   *
2800   * @since 3.6.0
2801   *
2802   * @global wpdb $wpdb WordPress database abstraction object.
2803   *
2804   * @param int              $object_id The ID of the object from which the terms will be removed.
2805   * @param string|int|array $terms     The slug(s) or ID(s) of the term(s) to remove.
2806   * @param array|string     $taxonomy  Taxonomy name.
2807   * @return bool|WP_Error True on success, false or WP_Error on failure.
2808   */
2809  function wp_remove_object_terms( $object_id, $terms, $taxonomy ) {
2810      global $wpdb;
2811  
2812      $object_id = (int) $object_id;
2813  
2814      if ( ! taxonomy_exists( $taxonomy ) ) {
2815          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
2816      }
2817  
2818      if ( ! is_array( $terms ) ) {
2819          $terms = array( $terms );
2820      }
2821  
2822      $tt_ids = array();
2823  
2824      foreach ( (array) $terms as $term ) {
2825          if ( '' === trim( $term ) ) {
2826              continue;
2827          }
2828  
2829          $term_info = term_exists( $term, $taxonomy );
2830          if ( ! $term_info ) {
2831              // Skip if a non-existent term ID is passed.
2832              if ( is_int( $term ) ) {
2833                  continue;
2834              }
2835          }
2836  
2837          if ( is_wp_error( $term_info ) ) {
2838              return $term_info;
2839          }
2840  
2841          $tt_ids[] = $term_info['term_taxonomy_id'];
2842      }
2843  
2844      if ( $tt_ids ) {
2845          $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'";
2846  
2847          /**
2848           * Fires immediately before an object-term relationship is deleted.
2849           *
2850           * @since 2.9.0
2851           * @since 4.7.0 Added the `$taxonomy` parameter.
2852           *
2853           * @param int   $object_id Object ID.
2854           * @param array $tt_ids    An array of term taxonomy IDs.
2855           * @param string $taxonomy  Taxonomy slug.
2856           */
2857          do_action( 'delete_term_relationships', $object_id, $tt_ids, $taxonomy );
2858  
2859          $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) );
2860  
2861          wp_cache_delete( $object_id, $taxonomy . '_relationships' );
2862          wp_cache_delete( 'last_changed', 'terms' );
2863  
2864          /**
2865           * Fires immediately after an object-term relationship is deleted.
2866           *
2867           * @since 2.9.0
2868           * @since 4.7.0 Added the `$taxonomy` parameter.
2869           *
2870           * @param int    $object_id Object ID.
2871           * @param array  $tt_ids    An array of term taxonomy IDs.
2872           * @param string $taxonomy  Taxonomy slug.
2873           */
2874          do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy );
2875  
2876          wp_update_term_count( $tt_ids, $taxonomy );
2877  
2878          return (bool) $deleted;
2879      }
2880  
2881      return false;
2882  }
2883  
2884  /**
2885   * Will make slug unique, if it isn't already.
2886   *
2887   * The `$slug` has to be unique global to every taxonomy, meaning that one
2888   * taxonomy term can't have a matching slug with another taxonomy term. Each
2889   * slug has to be globally unique for every taxonomy.
2890   *
2891   * The way this works is that if the taxonomy that the term belongs to is
2892   * hierarchical and has a parent, it will append that parent to the $slug.
2893   *
2894   * If that still doesn't return a unique slug, then it tries to append a number
2895   * until it finds a number that is truly unique.
2896   *
2897   * The only purpose for `$term` is for appending a parent, if one exists.
2898   *
2899   * @since 2.3.0
2900   *
2901   * @global wpdb $wpdb WordPress database abstraction object.
2902   *
2903   * @param string $slug The string that will be tried for a unique slug.
2904   * @param object $term The term object that the `$slug` will belong to.
2905   * @return string Will return a true unique slug.
2906   */
2907  function wp_unique_term_slug( $slug, $term ) {
2908      global $wpdb;
2909  
2910      $needs_suffix  = true;
2911      $original_slug = $slug;
2912  
2913      // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies.
2914      if ( ! term_exists( $slug ) || get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) {
2915          $needs_suffix = false;
2916      }
2917  
2918      /*
2919       * If the taxonomy supports hierarchy and the term has a parent, make the slug unique
2920       * by incorporating parent slugs.
2921       */
2922      $parent_suffix = '';
2923      if ( $needs_suffix && is_taxonomy_hierarchical( $term->taxonomy ) && ! empty( $term->parent ) ) {
2924          $the_parent = $term->parent;
2925          while ( ! empty( $the_parent ) ) {
2926              $parent_term = get_term( $the_parent, $term->taxonomy );
2927              if ( is_wp_error( $parent_term ) || empty( $parent_term ) ) {
2928                  break;
2929              }
2930              $parent_suffix .= '-' . $parent_term->slug;
2931              if ( ! term_exists( $slug . $parent_suffix ) ) {
2932                  break;
2933              }
2934  
2935              if ( empty( $parent_term->parent ) ) {
2936                  break;
2937              }
2938              $the_parent = $parent_term->parent;
2939          }
2940      }
2941  
2942      // If we didn't get a unique slug, try appending a number to make it unique.
2943  
2944      /**
2945       * Filters whether the proposed unique term slug is bad.
2946       *
2947       * @since 4.3.0
2948       *
2949       * @param bool   $needs_suffix Whether the slug needs to be made unique with a suffix.
2950       * @param string $slug         The slug.
2951       * @param object $term         Term object.
2952       */
2953      if ( apply_filters( 'wp_unique_term_slug_is_bad_slug', $needs_suffix, $slug, $term ) ) {
2954          if ( $parent_suffix ) {
2955              $slug .= $parent_suffix;
2956          }
2957  
2958          if ( ! empty( $term->term_id ) ) {
2959              $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id );
2960          } else {
2961              $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug );
2962          }
2963  
2964          if ( $wpdb->get_var( $query ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
2965              $num = 2;
2966              do {
2967                  $alt_slug = $slug . "-$num";
2968                  $num++;
2969                  $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) );
2970              } while ( $slug_check );
2971              $slug = $alt_slug;
2972          }
2973      }
2974  
2975      /**
2976       * Filters the unique term slug.
2977       *
2978       * @since 4.3.0
2979       *
2980       * @param string $slug          Unique term slug.
2981       * @param object $term          Term object.
2982       * @param string $original_slug Slug originally passed to the function for testing.
2983       */
2984      return apply_filters( 'wp_unique_term_slug', $slug, $term, $original_slug );
2985  }
2986  
2987  /**
2988   * Update term based on arguments provided.
2989   *
2990   * The `$args` will indiscriminately override all values with the same field name.
2991   * Care must be taken to not override important information need to update or
2992   * update will fail (or perhaps create a new term, neither would be acceptable).
2993   *
2994   * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not
2995   * defined in `$args` already.
2996   *
2997   * 'alias_of' will create a term group, if it doesn't already exist, and
2998   * update it for the `$term`.
2999   *
3000   * If the 'slug' argument in `$args` is missing, then the 'name' will be used.
3001   * If you set 'slug' and it isn't unique, then a WP_Error is returned.
3002   * If you don't pass any slug, then a unique one will be created.
3003   *
3004   * @since 2.3.0
3005   *
3006   * @global wpdb $wpdb WordPress database abstraction object.
3007   *
3008   * @param int          $term_id  The ID of the term.
3009   * @param string       $taxonomy The taxonomy of the term.
3010   * @param array|string $args {
3011   *     Optional. Array or string of arguments for updating a term.
3012   *
3013   *     @type string $alias_of    Slug of the term to make this term an alias of.
3014   *                               Default empty string. Accepts a term slug.
3015   *     @type string $description The term description. Default empty string.
3016   *     @type int    $parent      The id of the parent term. Default 0.
3017   *     @type string $slug        The term slug to use. Default empty string.
3018   * }
3019   * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`,
3020   *                        WP_Error otherwise.
3021   */
3022  function wp_update_term( $term_id, $taxonomy, $args = array() ) {
3023      global $wpdb;
3024  
3025      if ( ! taxonomy_exists( $taxonomy ) ) {
3026          return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
3027      }
3028  
3029      $term_id = (int) $term_id;
3030  
3031      // First, get all of the original args.
3032      $term = get_term( $term_id, $taxonomy );
3033  
3034      if ( is_wp_error( $term ) ) {
3035          return $term;
3036      }
3037  
3038      if ( ! $term ) {
3039          return new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
3040      }
3041  
3042      $term = (array) $term->data;
3043  
3044      // Escape data pulled from DB.
3045      $term = wp_slash( $term );
3046  
3047      // Merge old and new args with new args overwriting old ones.
3048      $args = array_merge( $term, $args );
3049  
3050      $defaults    = array(
3051          'alias_of'    => '',
3052          'description' => '',
3053          'parent'      => 0,
3054          'slug'        => '',
3055      );
3056      $args        = wp_parse_args( $args, $defaults );
3057      $args        = sanitize_term( $args, $taxonomy, 'db' );
3058      $parsed_args = $args;
3059  
3060      // expected_slashed ($name)
3061      $name        = wp_unslash( $args['name'] );
3062      $description = wp_unslash( $args['description'] );
3063  
3064      $parsed_args['name']        = $name;
3065      $parsed_args['description'] = $description;
3066  
3067      if ( '' === trim( $name ) ) {
3068          return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) );
3069      }
3070  
3071      if ( (int) $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) {
3072          return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) );
3073      }
3074  
3075      $empty_slug = false;
3076      if ( empty( $args['slug'] ) ) {
3077          $empty_slug = true;
3078          $slug       = sanitize_title( $name );
3079      } else {
3080          $slug = $args['slug'];
3081      }
3082  
3083      $parsed_args['slug'] = $slug;
3084  
3085      $term_group = isset( $parsed_args['term_group'] ) ? $parsed_args['term_group'] : 0;
3086      if ( $args['alias_of'] ) {
3087          $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy );
3088          if ( ! empty( $alias->term_group ) ) {
3089              // The alias we want is already in a group, so let's use that one.
3090              $term_group = $alias->term_group;
3091          } elseif ( ! empty( $alias->term_id ) ) {
3092              /*
3093               * The alias is not in a group, so we create a new one
3094               * and add the alias to it.
3095               */
3096              $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1;
3097  
3098              wp_update_term(
3099                  $alias->term_id,
3100                  $taxonomy,
3101                  array(
3102                      'term_group' => $term_group,
3103                  )
3104              );
3105          }
3106  
3107          $parsed_args['term_group'] = $term_group;
3108      }
3109  
3110      /**
3111       * Filters the term parent.
3112       *
3113       * Hook to this filter to see if it will cause a hierarchy loop.
3114       *
3115       * @since 3.1.0
3116       *
3117       * @param int    $parent      ID of the parent term.
3118       * @param int    $term_id     Term ID.
3119       * @param string $taxonomy    Taxonomy slug.
3120       * @param array  $parsed_args An array of potentially altered update arguments for the given term.
3121       * @param array  $args        An array of update arguments for the given term.
3122       */
3123      $parent = (int) apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args );
3124  
3125      // Check for duplicate slug.
3126      $duplicate = get_term_by( 'slug', $slug, $taxonomy );
3127      if ( $duplicate && $duplicate->term_id !== $term_id ) {
3128          // If an empty slug was passed or the parent changed, reset the slug to something unique.
3129          // Otherwise, bail.
3130          if ( $empty_slug || ( $parent !== (int) $term['parent'] ) ) {
3131              $slug = wp_unique_term_slug( $slug, (object) $args );
3132          } else {
3133              /* translators: %s: Taxonomy term slug. */
3134              return new WP_Error( 'duplicate_term_slug', sprintf( __( 'The slug &#8220;%s&#8221; is already in use by another term.' ), $slug ) );
3135          }
3136      }
3137  
3138      $tt_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) );
3139  
3140      // Check whether this is a shared term that needs splitting.
3141      $_term_id = _split_shared_term( $term_id, $tt_id );
3142      if ( ! is_wp_error( $_term_id ) ) {
3143          $term_id = $_term_id;
3144      }
3145  
3146      /**
3147       * Fires immediately before the given terms are edited.
3148       *
3149       * @since 2.9.0
3150       *
3151       * @param int    $term_id  Term ID.
3152       * @param string $taxonomy Taxonomy slug.
3153       */
3154      do_action( 'edit_terms', $term_id, $taxonomy );
3155  
3156      $data = compact( 'name', 'slug', 'term_group' );
3157  
3158      /**
3159       * Filters term data before it is updated in the database.
3160       *
3161       * @since 4.7.0
3162       *
3163       * @param array  $data     Term data to be updated.
3164       * @param int    $term_id  Term ID.
3165       * @param string $taxonomy Taxonomy slug.
3166       * @param array  $args     Arguments passed to wp_update_term().
3167       */
3168      $data = apply_filters( 'wp_update_term_data', $data, $term_id, $taxonomy, $args );
3169  
3170      $wpdb->update( $wpdb->terms, $data, compact( 'term_id' ) );
3171  
3172      if ( empty( $slug ) ) {
3173          $slug = sanitize_title( $name, $term_id );
3174          $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) );
3175      }
3176  
3177      /**
3178       * Fires immediately after a term is updated in the database, but before its
3179       * term-taxonomy relationship is updated.
3180       *
3181       * @since 2.9.0
3182       *
3183       * @param int    $term_id  Term ID
3184       * @param string $taxonomy Taxonomy slug.
3185       */
3186      do_action( 'edited_terms', $term_id, $taxonomy );
3187  
3188      /**
3189       * Fires immediate before a term-taxonomy relationship is updated.
3190       *
3191       * @since 2.9.0
3192       *
3193       * @param int    $tt_id    Term taxonomy ID.
3194       * @param string $taxonomy Taxonomy slug.
3195       */
3196      do_action( 'edit_term_taxonomy', $tt_id, $taxonomy );
3197  
3198      $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) );
3199  
3200      /**
3201       * Fires immediately after a term-taxonomy relationship is updated.
3202       *
3203       * @since 2.9.0
3204       *
3205       * @param int    $tt_id    Term taxonomy ID.
3206       * @param string $taxonomy Taxonomy slug.
3207       */
3208      do_action( 'edited_term_taxonomy', $tt_id, $taxonomy );
3209  
3210      /**
3211       * Fires after a term has been updated, but before the term cache has been cleaned.
3212       *
3213       * The {@see 'edit_$taxonomy'} hook is also available for targeting a specific
3214       * taxonomy.
3215       *
3216       * @since 2.3.0
3217       *
3218       * @param int    $term_id  Term ID.
3219       * @param int    $tt_id    Term taxonomy ID.
3220       * @param string $taxonomy Taxonomy slug.
3221       */
3222      do_action( 'edit_term', $term_id, $tt_id, $taxonomy );
3223  
3224      /**
3225       * Fires after a term in a specific taxonomy has been updated, but before the term
3226       * cache has been cleaned.
3227       *
3228       * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3229       *
3230       * Possible hook names include:
3231       *
3232       *  - `edit_category`
3233       *  - `edit_post_tag`
3234       *
3235       * @since 2.3.0
3236       *
3237       * @param int $term_id Term ID.
3238       * @param int $tt_id   Term taxonomy ID.
3239       */
3240      do_action( "edit_{$taxonomy}", $term_id, $tt_id );
3241  
3242      /** This filter is documented in wp-includes/taxonomy.php */
3243      $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id );
3244  
3245      clean_term_cache( $term_id, $taxonomy );
3246  
3247      /**
3248       * Fires after a term has been updated, and the term cache has been cleaned.
3249       *
3250       * The {@see 'edited_$taxonomy'} hook is also available for targeting a specific
3251       * taxonomy.
3252       *
3253       * @since 2.3.0
3254       *
3255       * @param int    $term_id  Term ID.
3256       * @param int    $tt_id    Term taxonomy ID.
3257       * @param string $taxonomy Taxonomy slug.
3258       */
3259      do_action( 'edited_term', $term_id, $tt_id, $taxonomy );
3260  
3261      /**
3262       * Fires after a term for a specific taxonomy has been updated, and the term
3263       * cache has been cleaned.
3264       *
3265       * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
3266       *
3267       * Possible hook names include:
3268       *
3269       *  - `edited_category`
3270       *  - `edited_post_tag`
3271       *
3272       * @since 2.3.0
3273       *
3274       * @param int $term_id Term ID.
3275       * @param int $tt_id   Term taxonomy ID.
3276       */
3277      do_action( "edited_{$taxonomy}", $term_id, $tt_id );
3278  
3279      /** This action is documented in wp-includes/taxonomy.php */
3280      do_action( 'saved_term', $term_id, $tt_id, $taxonomy, true );
3281  
3282      /** This action is documented in wp-includes/taxonomy.php */
3283      do_action( "saved_{$taxonomy}", $term_id, $tt_id, true );
3284  
3285      return array(
3286          'term_id'          => $term_id,
3287          'term_taxonomy_id' => $tt_id,
3288      );
3289  }
3290  
3291  /**
3292   * Enable or disable term counting.
3293   *
3294   * @since 2.5.0
3295   *
3296   * @param bool $defer Optional. Enable if true, disable if false.
3297   * @return bool Whether term counting is enabled or disabled.
3298   */
3299  function wp_defer_term_counting( $defer = null ) {
3300      static $_defer = false;
3301  
3302      if ( is_bool( $defer ) ) {
3303          $_defer = $defer;
3304          // Flush any deferred counts.
3305          if ( ! $defer ) {
3306              wp_update_term_count( null, null, true );
3307          }
3308      }
3309  
3310      return $_defer;
3311  }
3312  
3313  /**
3314   * Updates the amount of terms in taxonomy.
3315   *
3316   * If there is a taxonomy callback applied, then it will be called for updating
3317   * the count.
3318   *
3319   * The default action is to count what the amount of terms have the relationship
3320   * of term ID. Once that is done, then update the database.
3321   *
3322   * @since 2.3.0
3323   *
3324   * @param int|array $terms       The term_taxonomy_id of the terms.
3325   * @param string    $taxonomy    The context of the term.
3326   * @param bool      $do_deferred Whether to flush the deferred term counts too. Default false.
3327   * @return bool If no terms will return false, and if successful will return true.
3328   */
3329  function wp_update_term_count( $terms, $taxonomy, $do_deferred = false ) {
3330      static $_deferred = array();
3331  
3332      if ( $do_deferred ) {
3333          foreach ( (array) array_keys( $_deferred ) as $tax ) {
3334              wp_update_term_count_now( $_deferred[ $tax ], $tax );
3335              unset( $_deferred[ $tax ] );
3336          }
3337      }
3338  
3339      if ( empty( $terms ) ) {
3340          return false;
3341      }
3342  
3343      if ( ! is_array( $terms ) ) {
3344          $terms = array( $terms );
3345      }
3346  
3347      if ( wp_defer_term_counting() ) {
3348          if ( ! isset( $_deferred[ $taxonomy ] ) ) {
3349              $_deferred[ $taxonomy ] = array();
3350          }
3351          $_deferred[ $taxonomy ] = array_unique( array_merge( $_deferred[ $taxonomy ], $terms ) );
3352          return true;
3353      }
3354  
3355      return wp_update_term_count_now( $terms, $taxonomy );
3356  }
3357  
3358  /**
3359   * Perform term count update immediately.
3360   *
3361   * @since 2.5.0
3362   *
3363   * @param array  $terms    The term_taxonomy_id of terms to update.
3364   * @param string $taxonomy The context of the term.
3365   * @return true Always true when complete.
3366   */
3367  function wp_update_term_count_now( $terms, $taxonomy ) {
3368      $terms = array_map( 'intval', $terms );
3369  
3370      $taxonomy = get_taxonomy( $taxonomy );
3371      if ( ! empty( $taxonomy->update_count_callback ) ) {
3372          call_user_func( $taxonomy->update_count_callback, $terms, $taxonomy );
3373      } else {
3374          $object_types = (array) $taxonomy->object_type;
3375          foreach ( $object_types as &$object_type ) {
3376              if ( 0 === strpos( $object_type, 'attachment:' ) ) {
3377                  list( $object_type ) = explode( ':', $object_type );
3378              }
3379          }
3380  
3381          if ( array_filter( $object_types, 'post_type_exists' ) == $object_types ) {
3382              // Only post types are attached to this taxonomy.
3383              _update_post_term_count( $terms, $taxonomy );
3384          } else {
3385              // Default count updater.
3386              _update_generic_term_count( $terms, $taxonomy );
3387          }
3388      }
3389  
3390      clean_term_cache( $terms, '', false );
3391  
3392      return true;
3393  }
3394  
3395  //
3396  // Cache.
3397  //
3398  
3399  /**
3400   * Removes the taxonomy relationship to terms from the cache.
3401   *
3402   * Will remove the entire taxonomy relationship containing term `$object_id`. The
3403   * term IDs have to exist within the taxonomy `$object_type` for the deletion to
3404   * take place.
3405   *
3406   * @since 2.3.0
3407   *
3408   * @global bool $_wp_suspend_cache_invalidation
3409   *
3410   * @see get_object_taxonomies() for more on $object_type.
3411   *
3412   * @param int|array    $object_ids  Single or list of term object ID(s).
3413   * @param array|string $object_type The taxonomy object type.
3414   */
3415  function clean_object_term_cache( $object_ids, $object_type ) {
3416      global $_wp_suspend_cache_invalidation;
3417  
3418      if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
3419          return;
3420      }
3421  
3422      if ( ! is_array( $object_ids ) ) {
3423          $object_ids = array( $object_ids );
3424      }
3425  
3426      $taxonomies = get_object_taxonomies( $object_type );
3427  
3428      foreach ( $object_ids as $id ) {
3429          foreach ( $taxonomies as $taxonomy ) {
3430              wp_cache_delete( $id, "{$taxonomy}_relationships" );
3431          }
3432      }
3433  
3434      /**
3435       * Fires after the object term cache has been cleaned.
3436       *
3437       * @since 2.5.0
3438       *
3439       * @param array  $object_ids An array of object IDs.
3440       * @param string $object_type Object type.
3441       */
3442      do_action( 'clean_object_term_cache', $object_ids, $object_type );
3443  }
3444  
3445  /**
3446   * Will remove all of the term IDs from the cache.
3447   *
3448   * @since 2.3.0
3449   *
3450   * @global wpdb $wpdb                           WordPress database abstraction object.
3451   * @global bool $_wp_suspend_cache_invalidation
3452   *
3453   * @param int|int[] $ids            Single or array of term IDs.
3454   * @param string    $taxonomy       Optional. Taxonomy slug. Can be empty, in which case the taxonomies of the passed
3455   *                                  term IDs will be used. Default empty.
3456   * @param bool      $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual
3457   *                                  term object caches (false). Default true.
3458   */
3459  function clean_term_cache( $ids, $taxonomy = '', $clean_taxonomy = true ) {
3460      global $wpdb, $_wp_suspend_cache_invalidation;
3461  
3462      if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
3463          return;
3464      }
3465  
3466      if ( ! is_array( $ids ) ) {
3467          $ids = array( $ids );
3468      }
3469  
3470      $taxonomies = array();
3471      // If no taxonomy, assume tt_ids.
3472      if ( empty( $taxonomy ) ) {
3473          $tt_ids = array_map( 'intval', $ids );
3474          $tt_ids = implode( ', ', $tt_ids );
3475          $terms  = $wpdb->get_results( "SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)" );
3476          $ids    = array();
3477  
3478          foreach ( (array) $terms as $term ) {
3479              $taxonomies[] = $term->taxonomy;
3480              $ids[]        = $term->term_id;
3481              wp_cache_delete( $term->term_id, 'terms' );
3482          }
3483  
3484          $taxonomies = array_unique( $taxonomies );
3485      } else {
3486          $taxonomies = array( $taxonomy );
3487  
3488          foreach ( $taxonomies as $taxonomy ) {
3489              foreach ( $ids as $id ) {
3490                  wp_cache_delete( $id, 'terms' );
3491              }
3492          }
3493      }
3494  
3495      foreach ( $taxonomies as $taxonomy ) {
3496          if ( $clean_taxonomy ) {
3497              clean_taxonomy_cache( $taxonomy );
3498          }
3499  
3500          /**
3501           * Fires once after each taxonomy's term cache has been cleaned.
3502           *
3503           * @since 2.5.0
3504           * @since 4.5.0 Added the `$clean_taxonomy` parameter.
3505           *
3506           * @param array  $ids            An array of term IDs.
3507           * @param string $taxonomy       Taxonomy slug.
3508           * @param bool   $clean_taxonomy Whether or not to clean taxonomy-wide caches
3509           */
3510          do_action( 'clean_term_cache', $ids, $taxonomy, $clean_taxonomy );
3511      }
3512  
3513      wp_cache_set( 'last_changed', microtime(), 'terms' );
3514  }
3515  
3516  /**
3517   * Clean the caches for a taxonomy.
3518   *
3519   * @since 4.9.0
3520   *
3521   * @param string $taxonomy Taxonomy slug.
3522   */
3523  function clean_taxonomy_cache( $taxonomy ) {
3524      wp_cache_delete( 'all_ids', $taxonomy );
3525      wp_cache_delete( 'get', $taxonomy );
3526  
3527      // Regenerate cached hierarchy.
3528      delete_option( "{$taxonomy}_children" );
3529      _get_term_hierarchy( $taxonomy );
3530  
3531      /**
3532       * Fires after a taxonomy's caches have been cleaned.
3533       *
3534       * @since 4.9.0
3535       *
3536       * @param string $taxonomy Taxonomy slug.
3537       */
3538      do_action( 'clean_taxonomy_cache', $taxonomy );
3539  }
3540  
3541  /**
3542   * Retrieves the cached term objects for the given object ID.
3543   *
3544   * Upstream functions (like get_the_terms() and is_object_in_term()) are
3545   * responsible for populating the object-term relationship cache. The current
3546   * function only fetches relationship data that is already in the cache.
3547   *
3548   * @since 2.3.0
3549   * @since 4.7.0 Returns a `WP_Error` object if there's an error with
3550   *              any of the matched terms.
3551   *
3552   * @param int    $id       Term object ID, for example a post, comment, or user ID.
3553   * @param string $taxonomy Taxonomy name.
3554   * @return bool|WP_Term[]|WP_Error Array of `WP_Term` objects, if cached.
3555   *                                 False if cache is empty for `$taxonomy` and `$id`.
3556   *                                 WP_Error if get_term() returns an error object for any term.
3557   */
3558  function get_object_term_cache( $id, $taxonomy ) {
3559      $_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" );
3560  
3561      // We leave the priming of relationship caches to upstream functions.
3562      if ( false === $_term_ids ) {
3563          return false;
3564      }
3565  
3566      // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
3567      $term_ids = array();
3568      foreach ( $_term_ids as $term_id ) {
3569          if ( is_numeric( $term_id ) ) {
3570              $term_ids[] = (int) $term_id;
3571          } elseif ( isset( $term_id->term_id ) ) {
3572              $term_ids[] = (int) $term_id->term_id;
3573          }
3574      }
3575  
3576      // Fill the term objects.
3577      _prime_term_caches( $term_ids );
3578  
3579      $terms = array();
3580      foreach ( $term_ids as $term_id ) {
3581          $term = get_term( $term_id, $taxonomy );
3582          if ( is_wp_error( $term ) ) {
3583              return $term;
3584          }
3585  
3586          $terms[] = $term;
3587      }
3588  
3589      return $terms;
3590  }
3591  
3592  /**
3593   * Updates the cache for the given term object ID(s).
3594   *
3595   * Note: Due to performance concerns, great care should be taken to only update
3596   * term caches when necessary. Processing time can increase exponentially depending
3597   * on both the number of passed term IDs and the number of taxonomies those terms
3598   * belong to.
3599   *
3600   * Caches will only be updated for terms not already cached.
3601   *
3602   * @since 2.3.0
3603   *
3604   * @param string|int[]    $object_ids  Comma-separated list or array of term object IDs.
3605   * @param string|string[] $object_type The taxonomy object type or array of the same.
3606   * @return void|false Void on success or if the `$object_ids` parameter is empty,
3607   *                    false if all of the terms in `$object_ids` are already cached.
3608   */
3609  function update_object_term_cache( $object_ids, $object_type ) {
3610      if ( empty( $object_ids ) ) {
3611          return;
3612      }
3613  
3614      if ( ! is_array( $object_ids ) ) {
3615          $object_ids = explode( ',', $object_ids );
3616      }
3617  
3618      $object_ids     = array_map( 'intval', $object_ids );
3619      $non_cached_ids = array();
3620  
3621      $taxonomies = get_object_taxonomies( $object_type );
3622  
3623      foreach ( $taxonomies as $taxonomy ) {
3624          $cache_values = wp_cache_get_multiple( (array) $object_ids, "{$taxonomy}_relationships" );
3625  
3626          foreach ( $cache_values as $id => $value ) {
3627              if ( false === $value ) {
3628                  $non_cached_ids[] = $id;
3629              }
3630          }
3631      }
3632  
3633      if ( empty( $non_cached_ids ) ) {
3634          return false;
3635      }
3636  
3637      $non_cached_ids = array_unique( $non_cached_ids );
3638  
3639      $terms = wp_get_object_terms(
3640          $non_cached_ids,
3641          $taxonomies,
3642          array(
3643              'fields'                 => 'all_with_object_id',
3644              'orderby'                => 'name',
3645              'update_term_meta_cache' => false,
3646          )
3647      );
3648  
3649      $object_terms = array();
3650      foreach ( (array) $terms as $term ) {
3651          $object_terms[ $term->object_id ][ $term->taxonomy ][] = $term->term_id;
3652      }
3653  
3654      foreach ( $non_cached_ids as $id ) {
3655          foreach ( $taxonomies as $taxonomy ) {
3656              if ( ! isset( $object_terms[ $id ][ $taxonomy ] ) ) {
3657                  if ( ! isset( $object_terms[ $id ] ) ) {
3658                      $object_terms[ $id ] = array();
3659                  }
3660                  $object_terms[ $id ][ $taxonomy ] = array();
3661              }
3662          }
3663      }
3664  
3665      foreach ( $object_terms as $id => $value ) {
3666          foreach ( $value as $taxonomy => $terms ) {
3667              wp_cache_add( $id, $terms, "{$taxonomy}_relationships" );
3668          }
3669      }
3670  }
3671  
3672  /**
3673   * Updates Terms to Taxonomy in cache.
3674   *
3675   * @since 2.3.0
3676   *
3677   * @param WP_Term[] $terms    Array of term objects to change.
3678   * @param string    $taxonomy Not used.
3679   */
3680  function update_term_cache( $terms, $taxonomy = '' ) {
3681      foreach ( (array) $terms as $term ) {
3682          // Create a copy in case the array was passed by reference.
3683          $_term = clone $term;
3684  
3685          // Object ID should not be cached.
3686          unset( $_term->object_id );
3687  
3688          wp_cache_add( $term->term_id, $_term, 'terms' );
3689      }
3690  }
3691  
3692  //
3693  // Private.
3694  //
3695  
3696  /**
3697   * Retrieves children of taxonomy as Term IDs.
3698   *
3699   * @access private
3700   * @since 2.3.0
3701   *
3702   * @param string $taxonomy Taxonomy name.
3703   * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs.
3704   */
3705  function _get_term_hierarchy( $taxonomy ) {
3706      if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
3707          return array();
3708      }
3709      $children = get_option( "{$taxonomy}_children" );
3710  
3711      if ( is_array( $children ) ) {
3712          return $children;
3713      }
3714      $children = array();
3715      $terms    = get_terms(
3716          array(
3717              'taxonomy'               => $taxonomy,
3718              'get'                    => 'all',
3719              'orderby'                => 'id',
3720              'fields'                 => 'id=>parent',
3721              'update_term_meta_cache' => false,
3722          )
3723      );
3724      foreach ( $terms as $term_id => $parent ) {
3725          if ( $parent > 0 ) {
3726              $children[ $parent ][] = $term_id;
3727          }
3728      }
3729      update_option( "{$taxonomy}_children", $children );
3730  
3731      return $children;
3732  }
3733  
3734  /**
3735   * Get the subset of $terms that are descendants of $term_id.
3736   *
3737   * If `$terms` is an array of objects, then _get_term_children() returns an array of objects.
3738   * If `$terms` is an array of IDs, then _get_term_children() returns an array of IDs.
3739   *
3740   * @access private
3741   * @since 2.3.0
3742   *
3743   * @param int    $term_id   The ancestor term: all returned terms should be descendants of `$term_id`.
3744   * @param array  $terms     The set of terms - either an array of term objects or term IDs - from which those that
3745   *                          are descendants of $term_id will be chosen.
3746   * @param string $taxonomy  The taxonomy which determines the hierarchy of the terms.
3747   * @param array  $ancestors Optional. Term ancestors that have already been identified. Passed by reference, to keep
3748   *                          track of found terms when recursing the hierarchy. The array of located ancestors is used
3749   *                          to prevent infinite recursion loops. For performance, `term_ids` are used as array keys,
3750   *                          with 1 as value. Default empty array.
3751   * @return array|WP_Error The subset of $terms that are descendants of $term_id.
3752   */
3753  function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) {
3754      $empty_array = array();
3755      if ( empty( $terms ) ) {
3756          return $empty_array;
3757      }
3758  
3759      $term_id      = (int) $term_id;
3760      $term_list    = array();
3761      $has_children = _get_term_hierarchy( $taxonomy );
3762  
3763      if ( $term_id && ! isset( $has_children[ $term_id ] ) ) {
3764          return $empty_array;
3765      }
3766  
3767      // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred.
3768      if ( empty( $ancestors ) ) {
3769          $ancestors[ $term_id ] = 1;
3770      }
3771  
3772      foreach ( (array) $terms as $term ) {
3773          $use_id = false;
3774          if ( ! is_object( $term ) ) {
3775              $term = get_term( $term, $taxonomy );
3776              if ( is_wp_error( $term ) ) {
3777                  return $term;
3778              }
3779              $use_id = true;
3780          }
3781  
3782          // Don't recurse if we've already identified the term as a child - this indicates a loop.
3783          if ( isset( $ancestors[ $term->term_id ] ) ) {
3784              continue;
3785          }
3786  
3787          if ( (int) $term->parent === $term_id ) {
3788              if ( $use_id ) {
3789                  $term_list[] = $term->term_id;
3790              } else {
3791                  $term_list[] = $term;
3792              }
3793  
3794              if ( ! isset( $has_children[ $term->term_id ] ) ) {
3795                  continue;
3796              }
3797  
3798              $ancestors[ $term->term_id ] = 1;
3799  
3800              $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors );
3801              if ( $children ) {
3802                  $term_list = array_merge( $term_list, $children );
3803              }
3804          }
3805      }
3806  
3807      return $term_list;
3808  }
3809  
3810  /**
3811   * Add count of children to parent count.
3812   *
3813   * Recalculates term counts by including items from child terms. Assumes all
3814   * relevant children are already in the $terms argument.
3815   *
3816   * @access private
3817   * @since 2.3.0
3818   *
3819   * @global wpdb $wpdb WordPress database abstraction object.
3820   *
3821   * @param object[]|WP_Term[] $terms    List of term objects (passed by reference).
3822   * @param string             $taxonomy Term context.
3823   */
3824  function _pad_term_counts( &$terms, $taxonomy ) {
3825      global $wpdb;
3826  
3827      // This function only works for hierarchical taxonomies like post categories.
3828      if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
3829          return;
3830      }
3831  
3832      $term_hier = _get_term_hierarchy( $taxonomy );
3833  
3834      if ( empty( $term_hier ) ) {
3835          return;
3836      }
3837  
3838      $term_items  = array();
3839      $terms_by_id = array();
3840      $term_ids    = array();
3841  
3842      foreach ( (array) $terms as $key => $term ) {
3843          $terms_by_id[ $term->term_id ]       = & $terms[ $key ];
3844          $term_ids[ $term->term_taxonomy_id ] = $term->term_id;
3845      }
3846  
3847      // Get the object and term IDs and stick them in a lookup table.
3848      $tax_obj      = get_taxonomy( $taxonomy );
3849      $object_types = esc_sql( $tax_obj->object_type );
3850      $results      = $wpdb->get_results( "SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode( ',', array_keys( $term_ids ) ) . ") AND post_type IN ('" . implode( "', '", $object_types ) . "') AND post_status = 'publish'" );
3851  
3852      foreach ( $results as $row ) {
3853          $id = $term_ids[ $row->term_taxonomy_id ];
3854  
3855          $term_items[ $id ][ $row->object_id ] = isset( $term_items[ $id ][ $row->object_id ] ) ? ++$term_items[ $id ][ $row->object_id ] : 1;
3856      }
3857  
3858      // Touch every ancestor's lookup row for each post in each term.
3859      foreach ( $term_ids as $term_id ) {
3860          $child     = $term_id;
3861          $ancestors = array();
3862          while ( ! empty( $terms_by_id[ $child ] ) && $parent = $terms_by_id[ $child ]->parent ) {
3863              $ancestors[] = $child;
3864  
3865              if ( ! empty( $term_items[ $term_id ] ) ) {
3866                  foreach ( $term_items[ $term_id ] as $item_id => $touches ) {
3867                      $term_items[ $parent ][ $item_id ] = isset( $term_items[ $parent ][ $item_id ] ) ? ++$term_items[ $parent ][ $item_id ] : 1;
3868                  }
3869              }
3870  
3871              $child = $parent;
3872  
3873              if ( in_array( $parent, $ancestors, true ) ) {
3874                  break;
3875              }
3876          }
3877      }
3878  
3879      // Transfer the touched cells.
3880      foreach ( (array) $term_items as $id => $items ) {
3881          if ( isset( $terms_by_id[ $id ] ) ) {
3882              $terms_by_id[ $id ]->count = count( $items );
3883          }
3884      }
3885  }
3886  
3887  /**
3888   * Adds any terms from the given IDs to the cache that do not already exist in cache.
3889   *
3890   * @since 4.6.0
3891   * @access private
3892   *
3893   * @global wpdb $wpdb WordPress database abstraction object.
3894   *
3895   * @param array $term_ids          Array of term IDs.
3896   * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
3897   */
3898  function _prime_term_caches( $term_ids, $update_meta_cache = true ) {
3899      global $wpdb;
3900  
3901      $non_cached_ids = _get_non_cached_ids( $term_ids, 'terms' );
3902      if ( ! empty( $non_cached_ids ) ) {
3903          $fresh_terms = $wpdb->get_results( sprintf( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.term_id IN (%s)", implode( ',', array_map( 'intval', $non_cached_ids ) ) ) );
3904  
3905          update_term_cache( $fresh_terms, $update_meta_cache );
3906  
3907          if ( $update_meta_cache ) {
3908              update_termmeta_cache( $non_cached_ids );
3909          }
3910      }
3911  }
3912  
3913  //
3914  // Default callbacks.
3915  //
3916  
3917  /**
3918   * Will update term count based on object types of the current taxonomy.
3919   *
3920   * Private function for the default callback for post_tag and category
3921   * taxonomies.
3922   *
3923   * @access private
3924   * @since 2.3.0
3925   *
3926   * @global wpdb $wpdb WordPress database abstraction object.
3927   *
3928   * @param int[]       $terms    List of Term taxonomy IDs.
3929   * @param WP_Taxonomy $taxonomy Current taxonomy object of terms.
3930   */
3931  function _update_post_term_count( $terms, $taxonomy ) {
3932      global $wpdb;
3933  
3934      $object_types = (array) $taxonomy->object_type;
3935  
3936      foreach ( $object_types as &$object_type ) {
3937          list( $object_type ) = explode( ':', $object_type );
3938      }
3939  
3940      $object_types = array_unique( $object_types );
3941  
3942      $check_attachments = array_search( 'attachment', $object_types, true );
3943      if ( false !== $check_attachments ) {
3944          unset( $object_types[ $check_attachments ] );
3945          $check_attachments = true;
3946      }
3947  
3948      if ( $object_types ) {
3949          $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) );
3950      }
3951  
3952      $post_statuses = array( 'publish' );
3953  
3954      /**
3955       * Filters the post statuses for updating the term count.
3956       *
3957       * @since 5.7.0
3958       *
3959       * @param string[]    $post_statuses List of post statuses to include in the count. Default is 'publish'.
3960       * @param WP_Taxonomy $taxonomy      Current taxonomy object.
3961       */
3962      $post_statuses = esc_sql( apply_filters( 'update_post_term_count_statuses', $post_statuses, $taxonomy ) );
3963  
3964      foreach ( (array) $terms as $term ) {
3965          $count = 0;
3966  
3967          // Attachments can be 'inherit' status, we need to base count off the parent's status if so.
3968          if ( $check_attachments ) {
3969              // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration
3970              $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts p1 WHERE p1.ID = $wpdb->term_relationships.object_id AND ( post_status IN ('" . implode( "', '", $post_statuses ) . "') OR ( post_status = 'inherit' AND post_parent > 0 AND ( SELECT post_status FROM $wpdb->posts WHERE ID = p1.post_parent ) IN ('" . implode( "', '", $post_statuses ) . "') ) ) AND post_type = 'attachment' AND term_taxonomy_id = %d", $term ) );
3971          }
3972  
3973          if ( $object_types ) {
3974              // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration
3975              $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status IN ('" . implode( "', '", $post_statuses ) . "') AND post_type IN ('" . implode( "', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) );
3976          }
3977  
3978          /** This action is documented in wp-includes/taxonomy.php */
3979          do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
3980          $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
3981  
3982          /** This action is documented in wp-includes/taxonomy.php */
3983          do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
3984      }
3985  }
3986  
3987  /**
3988   * Will update term count based on number of objects.
3989   *
3990   * Default callback for the 'link_category' taxonomy.
3991   *
3992   * @since 3.3.0
3993   *
3994   * @global wpdb $wpdb WordPress database abstraction object.
3995   *
3996   * @param int[]       $terms    List of term taxonomy IDs.
3997   * @param WP_Taxonomy $taxonomy Current taxonomy object of terms.
3998   */
3999  function _update_generic_term_count( $terms, $taxonomy ) {
4000      global $wpdb;
4001  
4002      foreach ( (array) $terms as $term ) {
4003          $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
4004  
4005          /** This action is documented in wp-includes/taxonomy.php */
4006          do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
4007          $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
4008  
4009          /** This action is documented in wp-includes/taxonomy.php */
4010          do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
4011      }
4012  }
4013  
4014  /**
4015   * Create a new term for a term_taxonomy item that currently shares its term
4016   * with another term_taxonomy.
4017   *
4018   * @ignore
4019   * @since 4.2.0
4020   * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and
4021   *              `$term_taxonomy_id` can now accept objects.
4022   *
4023   * @global wpdb $wpdb WordPress database abstraction object.
4024   *
4025   * @param int|object $term_id          ID of the shared term, or the shared term object.
4026   * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object
4027   *                                     (corresponding to a row from the term_taxonomy table).
4028   * @param bool       $record           Whether to record data about the split term in the options table. The recording
4029   *                                     process has the potential to be resource-intensive, so during batch operations
4030   *                                     it can be beneficial to skip inline recording and do it just once, after the
4031   *                                     batch is processed. Only set this to `false` if you know what you are doing.
4032   *                                     Default: true.
4033   * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current
4034   *                      database schema), `$term_id` is returned. When the term is successfully split, the
4035   *                      new term_id is returned. A WP_Error is returned for miscellaneous errors.
4036   */
4037  function _split_shared_term( $term_id, $term_taxonomy_id, $record = true ) {
4038      global $wpdb;
4039  
4040      if ( is_object( $term_id ) ) {
4041          $shared_term = $term_id;
4042          $term_id     = (int) $shared_term->term_id;
4043      }
4044  
4045      if ( is_object( $term_taxonomy_id ) ) {
4046          $term_taxonomy    = $term_taxonomy_id;
4047          $term_taxonomy_id = (int) $term_taxonomy->term_taxonomy_id;
4048      }
4049  
4050      // If there are no shared term_taxonomy rows, there's nothing to do here.
4051      $shared_tt_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy tt WHERE tt.term_id = %d AND tt.term_taxonomy_id != %d", $term_id, $term_taxonomy_id ) );
4052  
4053      if ( ! $shared_tt_count ) {
4054          return $term_id;
4055      }
4056  
4057      /*
4058       * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id.
4059       * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db.
4060       */
4061      $check_term_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
4062      if ( $check_term_id !== $term_id ) {
4063          return $check_term_id;
4064      }
4065  
4066      // Pull up data about the currently shared slug, which we'll use to populate the new one.
4067      if ( empty( $shared_term ) ) {
4068          $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) );
4069      }
4070  
4071      $new_term_data = array(
4072          'name'       => $shared_term->name,
4073          'slug'       => $shared_term->slug,
4074          'term_group' => $shared_term->term_group,
4075      );
4076  
4077      if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) {
4078          return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error );
4079      }
4080  
4081      $new_term_id = (int) $wpdb->insert_id;
4082  
4083      // Update the existing term_taxonomy to point to the newly created term.
4084      $wpdb->update(
4085          $wpdb->term_taxonomy,
4086          array( 'term_id' => $new_term_id ),
4087          array( 'term_taxonomy_id' => $term_taxonomy_id )
4088      );
4089  
4090      // Reassign child terms to the new parent.
4091      if ( empty( $term_taxonomy ) ) {
4092          $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) );
4093      }
4094  
4095      $children_tt_ids = $wpdb->get_col( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE parent = %d AND taxonomy = %s", $term_id, $term_taxonomy->taxonomy ) );
4096      if ( ! empty( $children_tt_ids ) ) {
4097          foreach ( $children_tt_ids as $child_tt_id ) {
4098              $wpdb->update(
4099                  $wpdb->term_taxonomy,
4100                  array( 'parent' => $new_term_id ),
4101                  array( 'term_taxonomy_id' => $child_tt_id )
4102              );
4103              clean_term_cache( (int) $child_tt_id, '', false );
4104          }
4105      } else {
4106          // If the term has no children, we must force its taxonomy cache to be rebuilt separately.
4107          clean_term_cache( $new_term_id, $term_taxonomy->taxonomy, false );
4108      }
4109  
4110      clean_term_cache( $term_id, $term_taxonomy->taxonomy, false );
4111  
4112      /*
4113       * Taxonomy cache clearing is delayed to avoid race conditions that may occur when
4114       * regenerating the taxonomy's hierarchy tree.
4115       */
4116      $taxonomies_to_clean = array( $term_taxonomy->taxonomy );
4117  
4118      // Clean the cache for term taxonomies formerly shared with the current term.
4119      $shared_term_taxonomies = $wpdb->get_col( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
4120      $taxonomies_to_clean    = array_merge( $taxonomies_to_clean, $shared_term_taxonomies );
4121  
4122      foreach ( $taxonomies_to_clean as $taxonomy_to_clean ) {
4123          clean_taxonomy_cache( $taxonomy_to_clean );
4124      }
4125  
4126      // Keep a record of term_ids that have been split, keyed by old term_id. See wp_get_split_term().
4127      if ( $record ) {
4128          $split_term_data = get_option( '_split_terms', array() );
4129          if ( ! isset( $split_term_data[ $term_id ] ) ) {
4130              $split_term_data[ $term_id ] = array();
4131          }
4132  
4133          $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id;
4134          update_option( '_split_terms', $split_term_data );
4135      }
4136  
4137      // If we've just split the final shared term, set the "finished" flag.
4138      $shared_terms_exist = $wpdb->get_results(
4139          "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
4140           LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
4141           GROUP BY t.term_id
4142           HAVING term_tt_count > 1
4143           LIMIT 1"
4144      );
4145      if ( ! $shared_terms_exist ) {
4146          update_option( 'finished_splitting_shared_terms', true );
4147      }
4148  
4149      /**
4150       * Fires after a previously shared taxonomy term is split into two separate terms.
4151       *
4152       * @since 4.2.0
4153       *
4154       * @param int    $term_id          ID of the formerly shared term.
4155       * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
4156       * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4157       * @param string $taxonomy         Taxonomy for the split term.
4158       */
4159      do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy );
4160  
4161      return $new_term_id;
4162  }
4163  
4164  /**
4165   * Splits a batch of shared taxonomy terms.
4166   *
4167   * @since 4.3.0
4168   *
4169   * @global wpdb $wpdb WordPress database abstraction object.
4170   */
4171  function _wp_batch_split_terms() {
4172      global $wpdb;
4173  
4174      $lock_name = 'term_split.lock';
4175  
4176      // Try to lock.
4177      $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
4178  
4179      if ( ! $lock_result ) {
4180          $lock_result = get_option( $lock_name );
4181  
4182          // Bail if we were unable to create a lock, or if the existing lock is still valid.
4183          if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
4184              wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
4185              return;
4186          }
4187      }
4188  
4189      // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
4190      update_option( $lock_name, time() );
4191  
4192      // Get a list of shared terms (those with more than one associated row in term_taxonomy).
4193      $shared_terms = $wpdb->get_results(
4194          "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt
4195           LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
4196           GROUP BY t.term_id
4197           HAVING term_tt_count > 1
4198           LIMIT 10"
4199      );
4200  
4201      // No more terms, we're done here.
4202      if ( ! $shared_terms ) {
4203          update_option( 'finished_splitting_shared_terms', true );
4204          delete_option( $lock_name );
4205          return;
4206      }
4207  
4208      // Shared terms found? We'll need to run this script again.
4209      wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' );
4210  
4211      // Rekey shared term array for faster lookups.
4212      $_shared_terms = array();
4213      foreach ( $shared_terms as $shared_term ) {
4214          $term_id                   = (int) $shared_term->term_id;
4215          $_shared_terms[ $term_id ] = $shared_term;
4216      }
4217      $shared_terms = $_shared_terms;
4218  
4219      // Get term taxonomy data for all shared terms.
4220      $shared_term_ids = implode( ',', array_keys( $shared_terms ) );
4221      $shared_tts      = $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})" );
4222  
4223      // Split term data recording is slow, so we do it just once, outside the loop.
4224      $split_term_data    = get_option( '_split_terms', array() );
4225      $skipped_first_term = array();
4226      $taxonomies         = array();
4227      foreach ( $shared_tts as $shared_tt ) {
4228          $term_id = (int) $shared_tt->term_id;
4229  
4230          // Don't split the first tt belonging to a given term_id.
4231          if ( ! isset( $skipped_first_term[ $term_id ] ) ) {
4232              $skipped_first_term[ $term_id ] = 1;
4233              continue;
4234          }
4235  
4236          if ( ! isset( $split_term_data[ $term_id ] ) ) {
4237              $split_term_data[ $term_id ] = array();
4238          }
4239  
4240          // Keep track of taxonomies whose hierarchies need flushing.
4241          if ( ! isset( $taxonomies[ $shared_tt->taxonomy ] ) ) {
4242              $taxonomies[ $shared_tt->taxonomy ] = 1;
4243          }
4244  
4245          // Split the term.
4246          $split_term_data[ $term_id ][ $shared_tt->taxonomy ] = _split_shared_term( $shared_terms[ $term_id ], $shared_tt, false );
4247      }
4248  
4249      // Rebuild the cached hierarchy for each affected taxonomy.
4250      foreach ( array_keys( $taxonomies ) as $tax ) {
4251          delete_option( "{$tax}_children" );
4252          _get_term_hierarchy( $tax );
4253      }
4254  
4255      update_option( '_split_terms', $split_term_data );
4256  
4257      delete_option( $lock_name );
4258  }
4259  
4260  /**
4261   * In order to avoid the _wp_batch_split_terms() job being accidentally removed,
4262   * check that it's still scheduled while we haven't finished splitting terms.
4263   *
4264   * @ignore
4265   * @since 4.3.0
4266   */
4267  function _wp_check_for_scheduled_split_terms() {
4268      if ( ! get_option( 'finished_splitting_shared_terms' ) && ! wp_next_scheduled( 'wp_split_shared_term_batch' ) ) {
4269          wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_split_shared_term_batch' );
4270      }
4271  }
4272  
4273  /**
4274   * Check default categories when a term gets split to see if any of them need to be updated.
4275   *
4276   * @ignore
4277   * @since 4.2.0
4278   *
4279   * @param int    $term_id          ID of the formerly shared term.
4280   * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
4281   * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4282   * @param string $taxonomy         Taxonomy for the split term.
4283   */
4284  function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4285      if ( 'category' !== $taxonomy ) {
4286          return;
4287      }
4288  
4289      foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) {
4290          if ( (int) get_option( $option, -1 ) === $term_id ) {
4291              update_option( $option, $new_term_id );
4292          }
4293      }
4294  }
4295  
4296  /**
4297   * Check menu items when a term gets split to see if any of them need to be updated.
4298   *
4299   * @ignore
4300   * @since 4.2.0
4301   *
4302   * @global wpdb $wpdb WordPress database abstraction object.
4303   *
4304   * @param int    $term_id          ID of the formerly shared term.
4305   * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
4306   * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4307   * @param string $taxonomy         Taxonomy for the split term.
4308   */
4309  function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4310      global $wpdb;
4311      $post_ids = $wpdb->get_col(
4312          $wpdb->prepare(
4313              "SELECT m1.post_id
4314          FROM {$wpdb->postmeta} AS m1
4315              INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id )
4316              INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id )
4317          WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' )
4318              AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = %s )
4319              AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )",
4320              $taxonomy,
4321              $term_id
4322          )
4323      );
4324  
4325      if ( $post_ids ) {
4326          foreach ( $post_ids as $post_id ) {
4327              update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id );
4328          }
4329      }
4330  }
4331  
4332  /**
4333   * If the term being split is a nav_menu, change associations.
4334   *
4335   * @ignore
4336   * @since 4.3.0
4337   *
4338   * @param int    $term_id          ID of the formerly shared term.
4339   * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
4340   * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
4341   * @param string $taxonomy         Taxonomy for the split term.
4342   */
4343  function _wp_check_split_nav_menu_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) {
4344      if ( 'nav_menu' !== $taxonomy ) {
4345          return;
4346      }
4347  
4348      // Update menu locations.
4349      $locations = get_nav_menu_locations();
4350      foreach ( $locations as $location => $menu_id ) {
4351          if ( $term_id === $menu_id ) {
4352              $locations[ $location ] = $new_term_id;
4353          }
4354      }
4355      set_theme_mod( 'nav_menu_locations', $locations );
4356  }
4357  
4358  /**
4359   * Get data about terms that previously shared a single term_id, but have since been split.
4360   *
4361   * @since 4.2.0
4362   *
4363   * @param int $old_term_id Term ID. This is the old, pre-split term ID.
4364   * @return array Array of new term IDs, keyed by taxonomy.
4365   */
4366  function wp_get_split_terms( $old_term_id ) {
4367      $split_terms = get_option( '_split_terms', array() );
4368  
4369      $terms = array();
4370      if ( isset( $split_terms[ $old_term_id ] ) ) {
4371          $terms = $split_terms[ $old_term_id ];
4372      }
4373  
4374      return $terms;
4375  }
4376  
4377  /**
4378   * Get the new term ID corresponding to a previously split term.
4379   *
4380   * @since 4.2.0
4381   *
4382   * @param int    $old_term_id Term ID. This is the old, pre-split term ID.
4383   * @param string $taxonomy    Taxonomy that the term belongs to.
4384   * @return int|false If a previously split term is found corresponding to the old term_id and taxonomy,
4385   *                   the new term_id will be returned. If no previously split term is found matching
4386   *                   the parameters, returns false.
4387   */
4388  function wp_get_split_term( $old_term_id, $taxonomy ) {
4389      $split_terms = wp_get_split_terms( $old_term_id );
4390  
4391      $term_id = false;
4392      if ( isset( $split_terms[ $taxonomy ] ) ) {
4393          $term_id = (int) $split_terms[ $taxonomy ];
4394      }
4395  
4396      return $term_id;
4397  }
4398  
4399  /**
4400   * Determine whether a term is shared between multiple taxonomies.
4401   *
4402   * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or
4403   * other delays in upgrade routines may cause shared terms to remain.
4404   *
4405   * @since 4.4.0
4406   *
4407   * @param int $term_id Term ID.
4408   * @return bool Returns false if a term is not shared between multiple taxonomies or
4409   *              if splitting shared taxonomy terms is finished.
4410   */
4411  function wp_term_is_shared( $term_id ) {
4412      global $wpdb;
4413  
4414      if ( get_option( 'finished_splitting_shared_terms' ) ) {
4415          return false;
4416      }
4417  
4418      $tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) );
4419  
4420      return $tt_count > 1;
4421  }
4422  
4423  /**
4424   * Generate a permalink for a taxonomy term archive.
4425   *
4426   * @since 2.5.0
4427   *
4428   * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
4429   *
4430   * @param WP_Term|int|string $term     The term object, ID, or slug whose link will be retrieved.
4431   * @param string             $taxonomy Optional. Taxonomy. Default empty.
4432   * @return string|WP_Error URL of the taxonomy term archive on success, WP_Error if term does not exist.
4433   */
4434  function get_term_link( $term, $taxonomy = '' ) {
4435      global $wp_rewrite;
4436  
4437      if ( ! is_object( $term ) ) {
4438          if ( is_int( $term ) ) {
4439              $term = get_term( $term, $taxonomy );
4440          } else {
4441              $term = get_term_by( 'slug', $term, $taxonomy );
4442          }
4443      }
4444  
4445      if ( ! is_object( $term ) ) {
4446          $term = new WP_Error( 'invalid_term', __( 'Empty Term.' ) );
4447      }
4448  
4449      if ( is_wp_error( $term ) ) {
4450          return $term;
4451      }
4452  
4453      $taxonomy = $term->taxonomy;
4454  
4455      $termlink = $wp_rewrite->get_extra_permastruct( $taxonomy );
4456  
4457      /**
4458       * Filters the permalink structure for a term before token replacement occurs.
4459       *
4460       * @since 4.9.0
4461       *
4462       * @param string  $termlink The permalink structure for the term's taxonomy.
4463       * @param WP_Term $term     The term object.
4464       */
4465      $termlink = apply_filters( 'pre_term_link', $termlink, $term );
4466  
4467      $slug = $term->slug;
4468      $t    = get_taxonomy( $taxonomy );
4469  
4470      if ( empty( $termlink ) ) {
4471          if ( 'category' === $taxonomy ) {
4472              $termlink = '?cat=' . $term->term_id;
4473          } elseif ( $t->query_var ) {
4474              $termlink = "?$t->query_var=$slug";
4475          } else {
4476              $termlink = "?taxonomy=$taxonomy&term=$slug";
4477          }
4478          $termlink = home_url( $termlink );
4479      } else {
4480          if ( ! empty( $t->rewrite['hierarchical'] ) ) {
4481              $hierarchical_slugs = array();
4482              $ancestors          = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
4483              foreach ( (array) $ancestors as $ancestor ) {
4484                  $ancestor_term        = get_term( $ancestor, $taxonomy );
4485                  $hierarchical_slugs[] = $ancestor_term->slug;
4486              }
4487              $hierarchical_slugs   = array_reverse( $hierarchical_slugs );
4488              $hierarchical_slugs[] = $slug;
4489              $termlink             = str_replace( "%$taxonomy%", implode( '/', $hierarchical_slugs ), $termlink );
4490          } else {
4491              $termlink = str_replace( "%$taxonomy%", $slug, $termlink );
4492          }
4493          $termlink = home_url( user_trailingslashit( $termlink, 'category' ) );
4494      }
4495  
4496      // Back compat filters.
4497      if ( 'post_tag' === $taxonomy ) {
4498  
4499          /**
4500           * Filters the tag link.
4501           *
4502           * @since 2.3.0
4503           * @since 2.5.0 Deprecated in favor of {@see 'term_link'} filter.
4504           * @since 5.4.1 Restored (un-deprecated).
4505           *
4506           * @param string $termlink Tag link URL.
4507           * @param int    $term_id  Term ID.
4508           */
4509          $termlink = apply_filters( 'tag_link', $termlink, $term->term_id );
4510      } elseif ( 'category' === $taxonomy ) {
4511  
4512          /**
4513           * Filters the category link.
4514           *
4515           * @since 1.5.0
4516           * @since 2.5.0 Deprecated in favor of {@see 'term_link'} filter.
4517           * @since 5.4.1 Restored (un-deprecated).
4518           *
4519           * @param string $termlink Category link URL.
4520           * @param int    $term_id  Term ID.
4521           */
4522          $termlink = apply_filters( 'category_link', $termlink, $term->term_id );
4523      }
4524  
4525      /**
4526       * Filters the term link.
4527       *
4528       * @since 2.5.0
4529       *
4530       * @param string  $termlink Term link URL.
4531       * @param WP_Term $term     Term object.
4532       * @param string  $taxonomy Taxonomy slug.
4533       */
4534      return apply_filters( 'term_link', $termlink, $term, $taxonomy );
4535  }
4536  
4537  /**
4538   * Display the taxonomies of a post with available options.
4539   *
4540   * This function can be used within the loop to display the taxonomies for a
4541   * post without specifying the Post ID. You can also use it outside the Loop to
4542   * display the taxonomies for a specific post.
4543   *
4544   * @since 2.5.0
4545   *
4546   * @param array $args {
4547   *     Arguments about which post to use and how to format the output. Shares all of the arguments
4548   *     supported by get_the_taxonomies(), in addition to the following.
4549   *
4550   *     @type  int|WP_Post $post   Post ID or object to get taxonomies of. Default current post.
4551   *     @type  string      $before Displays before the taxonomies. Default empty string.
4552   *     @type  string      $sep    Separates each taxonomy. Default is a space.
4553   *     @type  string      $after  Displays after the taxonomies. Default empty string.
4554   * }
4555   */
4556  function the_taxonomies( $args = array() ) {
4557      $defaults = array(
4558          'post'   => 0,
4559          'before' => '',
4560          'sep'    => ' ',
4561          'after'  => '',
4562      );
4563  
4564      $parsed_args = wp_parse_args( $args, $defaults );
4565  
4566      echo $parsed_args['before'] . implode( $parsed_args['sep'], get_the_taxonomies( $parsed_args['post'], $parsed_args ) ) . $parsed_args['after'];
4567  }
4568  
4569  /**
4570   * Retrieve all taxonomies associated with a post.
4571   *
4572   * This function can be used within the loop. It will also return an array of
4573   * the taxonomies with links to the taxonomy and name.
4574   *
4575   * @since 2.5.0
4576   *
4577   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4578   * @param array       $args {
4579   *           Optional. Arguments about how to format the list of taxonomies. Default empty array.
4580   *
4581   *     @type string $template      Template for displaying a taxonomy label and list of terms.
4582   *                                 Default is "Label: Terms."
4583   *     @type string $term_template Template for displaying a single term in the list. Default is the term name
4584   *                                 linked to its archive.
4585   * }
4586   * @return array List of taxonomies.
4587   */
4588  function get_the_taxonomies( $post = 0, $args = array() ) {
4589      $post = get_post( $post );
4590  
4591      $args = wp_parse_args(
4592          $args,
4593          array(
4594              /* translators: %s: Taxonomy label, %l: List of terms formatted as per $term_template. */
4595              'template'      => __( '%s: %l.' ),
4596              'term_template' => '<a href="%1$s">%2$s</a>',
4597          )
4598      );
4599  
4600      $taxonomies = array();
4601  
4602      if ( ! $post ) {
4603          return $taxonomies;
4604      }
4605  
4606      foreach ( get_object_taxonomies( $post ) as $taxonomy ) {
4607          $t = (array) get_taxonomy( $taxonomy );
4608          if ( empty( $t['label'] ) ) {
4609              $t['label'] = $taxonomy;
4610          }
4611          if ( empty( $t['args'] ) ) {
4612              $t['args'] = array();
4613          }
4614          if ( empty( $t['template'] ) ) {
4615              $t['template'] = $args['template'];
4616          }
4617          if ( empty( $t['term_template'] ) ) {
4618              $t['term_template'] = $args['term_template'];
4619          }
4620  
4621          $terms = get_object_term_cache( $post->ID, $taxonomy );
4622          if ( false === $terms ) {
4623              $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] );
4624          }
4625          $links = array();
4626  
4627          foreach ( $terms as $term ) {
4628              $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name );
4629          }
4630          if ( $links ) {
4631              $taxonomies[ $taxonomy ] = wp_sprintf( $t['template'], $t['label'], $links, $terms );
4632          }
4633      }
4634      return $taxonomies;
4635  }
4636  
4637  /**
4638   * Retrieve all taxonomy names for the given post.
4639   *
4640   * @since 2.5.0
4641   *
4642   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
4643   * @return string[] An array of all taxonomy names for the given post.
4644   */
4645  function get_post_taxonomies( $post = 0 ) {
4646      $post = get_post( $post );
4647  
4648      return get_object_taxonomies( $post );
4649  }
4650  
4651  /**
4652   * Determine if the given object is associated with any of the given terms.
4653   *
4654   * The given terms are checked against the object's terms' term_ids, names and slugs.
4655   * Terms given as integers will only be checked against the object's terms' term_ids.
4656   * If no terms are given, determines if object is associated with any terms in the given taxonomy.
4657   *
4658   * @since 2.7.0
4659   *
4660   * @param int                       $object_id ID of the object (post ID, link ID, ...).
4661   * @param string                    $taxonomy  Single taxonomy name.
4662   * @param int|string|int[]|string[] $terms     Optional. Term ID, name, slug, or array of such
4663   *                                             to check against. Default null.
4664   * @return bool|WP_Error WP_Error on input error.
4665   */
4666  function is_object_in_term( $object_id, $taxonomy, $terms = null ) {
4667      $object_id = (int) $object_id;
4668      if ( ! $object_id ) {
4669          return new WP_Error( 'invalid_object', __( 'Invalid object ID.' ) );
4670      }
4671  
4672      $object_terms = get_object_term_cache( $object_id, $taxonomy );
4673      if ( false === $object_terms ) {
4674          $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) );
4675          if ( is_wp_error( $object_terms ) ) {
4676              return $object_terms;
4677          }
4678  
4679          wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" );
4680      }
4681  
4682      if ( is_wp_error( $object_terms ) ) {
4683          return $object_terms;
4684      }
4685      if ( empty( $object_terms ) ) {
4686          return false;
4687      }
4688      if ( empty( $terms ) ) {
4689          return ( ! empty( $object_terms ) );
4690      }
4691  
4692      $terms = (array) $terms;
4693  
4694      $ints = array_filter( $terms, 'is_int' );
4695      if ( $ints ) {
4696          $strs = array_diff( $terms, $ints );
4697      } else {
4698          $strs =& $terms;
4699      }
4700  
4701      foreach ( $object_terms as $object_term ) {
4702          // If term is an int, check against term_ids only.
4703          if ( $ints && in_array( $object_term->term_id, $ints, true ) ) {
4704              return true;
4705          }
4706  
4707          if ( $strs ) {
4708              // Only check numeric strings against term_id, to avoid false matches due to type juggling.
4709              $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) );
4710              if ( in_array( $object_term->term_id, $numeric_strs, true ) ) {
4711                  return true;
4712              }
4713  
4714              if ( in_array( $object_term->name, $strs, true ) ) {
4715                  return true;
4716              }
4717              if ( in_array( $object_term->slug, $strs, true ) ) {
4718                  return true;
4719              }
4720          }
4721      }
4722  
4723      return false;
4724  }
4725  
4726  /**
4727   * Determine if the given object type is associated with the given taxonomy.
4728   *
4729   * @since 3.0.0
4730   *
4731   * @param string $object_type Object type string.
4732   * @param string $taxonomy    Single taxonomy name.
4733   * @return bool True if object is associated with the taxonomy, otherwise false.
4734   */
4735  function is_object_in_taxonomy( $object_type, $taxonomy ) {
4736      $taxonomies = get_object_taxonomies( $object_type );
4737      if ( empty( $taxonomies ) ) {
4738          return false;
4739      }
4740      return in_array( $taxonomy, $taxonomies, true );
4741  }
4742  
4743  /**
4744   * Get an array of ancestor IDs for a given object.
4745   *
4746   * @since 3.1.0
4747   * @since 4.1.0 Introduced the `$resource_type` argument.
4748   *
4749   * @param int    $object_id     Optional. The ID of the object. Default 0.
4750   * @param string $object_type   Optional. The type of object for which we'll be retrieving
4751   *                              ancestors. Accepts a post type or a taxonomy name. Default empty.
4752   * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type'
4753   *                              or 'taxonomy'. Default empty.
4754   * @return int[] An array of IDs of ancestors from lowest to highest in the hierarchy.
4755   */
4756  function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) {
4757      $object_id = (int) $object_id;
4758  
4759      $ancestors = array();
4760  
4761      if ( empty( $object_id ) ) {
4762  
4763          /** This filter is documented in wp-includes/taxonomy.php */
4764          return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4765      }
4766  
4767      if ( ! $resource_type ) {
4768          if ( is_taxonomy_hierarchical( $object_type ) ) {
4769              $resource_type = 'taxonomy';
4770          } elseif ( post_type_exists( $object_type ) ) {
4771              $resource_type = 'post_type';
4772          }
4773      }
4774  
4775      if ( 'taxonomy' === $resource_type ) {
4776          $term = get_term( $object_id, $object_type );
4777          while ( ! is_wp_error( $term ) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors, true ) ) {
4778              $ancestors[] = (int) $term->parent;
4779              $term        = get_term( $term->parent, $object_type );
4780          }
4781      } elseif ( 'post_type' === $resource_type ) {
4782          $ancestors = get_post_ancestors( $object_id );
4783      }
4784  
4785      /**
4786       * Filters a given object's ancestors.
4787       *
4788       * @since 3.1.0
4789       * @since 4.1.1 Introduced the `$resource_type` parameter.
4790       *
4791       * @param int[]  $ancestors     An array of IDs of object ancestors.
4792       * @param int    $object_id     Object ID.
4793       * @param string $object_type   Type of object.
4794       * @param string $resource_type Type of resource $object_type is.
4795       */
4796      return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type );
4797  }
4798  
4799  /**
4800   * Returns the term's parent's term_ID.
4801   *
4802   * @since 3.1.0
4803   *
4804   * @param int    $term_id  Term ID.
4805   * @param string $taxonomy Taxonomy name.
4806   * @return int|false Parent term ID on success, false on failure.
4807   */
4808  function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) {
4809      $term = get_term( $term_id, $taxonomy );
4810      if ( ! $term || is_wp_error( $term ) ) {
4811          return false;
4812      }
4813      return (int) $term->parent;
4814  }
4815  
4816  /**
4817   * Checks the given subset of the term hierarchy for hierarchy loops.
4818   * Prevents loops from forming and breaks those that it finds.
4819   *
4820   * Attached to the {@see 'wp_update_term_parent'} filter.
4821   *
4822   * @since 3.1.0
4823   *
4824   * @param int    $parent   `term_id` of the parent for the term we're checking.
4825   * @param int    $term_id  The term we're checking.
4826   * @param string $taxonomy The taxonomy of the term we're checking.
4827   * @return int The new parent for the term.
4828   */
4829  function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) {
4830      // Nothing fancy here - bail.
4831      if ( ! $parent ) {
4832          return 0;
4833      }
4834  
4835      // Can't be its own parent.
4836      if ( $parent === $term_id ) {
4837          return 0;
4838      }
4839  
4840      // Now look for larger loops.
4841      $loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) );
4842      if ( ! $loop ) {
4843          return $parent; // No loop.
4844      }
4845  
4846      // Setting $parent to the given value causes a loop.
4847      if ( isset( $loop[ $term_id ] ) ) {
4848          return 0;
4849      }
4850  
4851      // There's a loop, but it doesn't contain $term_id. Break the loop.
4852      foreach ( array_keys( $loop ) as $loop_member ) {
4853          wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) );
4854      }
4855  
4856      return $parent;
4857  }
4858  
4859  /**
4860   * Determines whether a taxonomy is considered "viewable".
4861   *
4862   * @since 5.1.0
4863   *
4864   * @param string|WP_Taxonomy $taxonomy Taxonomy name or object.
4865   * @return bool Whether the taxonomy should be considered viewable.
4866   */
4867  function is_taxonomy_viewable( $taxonomy ) {
4868      if ( is_scalar( $taxonomy ) ) {
4869          $taxonomy = get_taxonomy( $taxonomy );
4870          if ( ! $taxonomy ) {
4871              return false;
4872          }
4873      }
4874  
4875      return $taxonomy->publicly_queryable;
4876  }
4877  
4878  /**
4879   * Sets the last changed time for the 'terms' cache group.
4880   *
4881   * @since 5.0.0
4882   */
4883  function wp_cache_set_terms_last_changed() {
4884      wp_cache_set( 'last_changed', microtime(), 'terms' );
4885  }
4886  
4887  /**
4888   * Aborts calls to term meta if it is not supported.
4889   *
4890   * @since 5.0.0
4891   *
4892   * @param mixed $check Skip-value for whether to proceed term meta function execution.
4893   * @return mixed Original value of $check, or false if term meta is not supported.
4894   */
4895  function wp_check_term_meta_support_prefilter( $check ) {
4896      if ( get_option( 'db_version' ) < 34370 ) {
4897          return false;
4898      }
4899  
4900      return $check;
4901  }