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