[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Tue Jan 26 08:20:01 2021 Cross-referenced by PHPXref