[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Sun Sep 22 08:20:01 2019 Cross-referenced by PHPXref 0.7