[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Tue Apr 7 01:00:07 2020 Cross-referenced by PHPXref 0.7.1