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