[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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