[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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