[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Mon Aug 3 08:20:02 2020 Cross-referenced by PHPXref