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