[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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