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