| [ 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: non-negative-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 * @phpstan-param object{ term_id: non-negative-int, term_taxonomy_id: int|numeric-string }|null $duplicate_term 2812 */ 2813 $duplicate_term = apply_filters( 'wp_insert_term_duplicate_term_check', $duplicate_term, $term, $taxonomy, $args, $tt_id ); 2814 2815 if ( $duplicate_term ) { 2816 $wpdb->delete( $wpdb->terms, array( 'term_id' => $term_id ) ); 2817 $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) ); 2818 2819 $term_id = (int) $duplicate_term->term_id; 2820 $tt_id = (int) $duplicate_term->term_taxonomy_id; 2821 2822 clean_term_cache( $term_id, $taxonomy ); 2823 return array( 2824 'term_id' => $term_id, 2825 'term_taxonomy_id' => $tt_id, 2826 ); 2827 } 2828 2829 /** 2830 * Fires immediately after a new term is created, before the term cache is cleaned. 2831 * 2832 * The {@see 'create_$taxonomy'} hook is also available for targeting a specific 2833 * taxonomy. 2834 * 2835 * @since 2.3.0 2836 * @since 6.1.0 The `$args` parameter was added. 2837 * 2838 * @param int $term_id Term ID. 2839 * @param int $tt_id Term taxonomy ID. 2840 * @param string $taxonomy Taxonomy slug. 2841 * @param array $args Arguments passed to wp_insert_term(). 2842 */ 2843 do_action( 'create_term', $term_id, $tt_id, $taxonomy, $args ); 2844 2845 /** 2846 * Fires after a new term is created for a specific taxonomy. 2847 * 2848 * The dynamic portion of the hook name, `$taxonomy`, refers 2849 * to the slug of the taxonomy the term was created for. 2850 * 2851 * Possible hook names include: 2852 * 2853 * - `create_category` 2854 * - `create_post_tag` 2855 * 2856 * @since 2.3.0 2857 * @since 6.1.0 The `$args` parameter was added. 2858 * 2859 * @param int $term_id Term ID. 2860 * @param int $tt_id Term taxonomy ID. 2861 * @param array $args Arguments passed to wp_insert_term(). 2862 */ 2863 do_action( "create_{$taxonomy}", $term_id, $tt_id, $args ); 2864 2865 /** 2866 * Filters the term ID after a new term is created. 2867 * 2868 * @since 2.3.0 2869 * @since 6.1.0 The `$args` parameter was added. 2870 * 2871 * @param int $term_id Term ID. 2872 * @param int $tt_id Term taxonomy ID. 2873 * @param array $args Arguments passed to wp_insert_term(). 2874 * 2875 * @phpstan-param non-negative-int $term_id 2876 */ 2877 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id, $args ); 2878 2879 clean_term_cache( $term_id, $taxonomy ); 2880 2881 /** 2882 * Fires after a new term is created, and after the term cache has been cleaned. 2883 * 2884 * The {@see 'created_$taxonomy'} hook is also available for targeting a specific 2885 * taxonomy. 2886 * 2887 * @since 2.3.0 2888 * @since 6.1.0 The `$args` parameter was added. 2889 * 2890 * @param int $term_id Term ID. 2891 * @param int $tt_id Term taxonomy ID. 2892 * @param string $taxonomy Taxonomy slug. 2893 * @param array $args Arguments passed to wp_insert_term(). 2894 */ 2895 do_action( 'created_term', $term_id, $tt_id, $taxonomy, $args ); 2896 2897 /** 2898 * Fires after a new term in a specific taxonomy is created, and after the term 2899 * cache has been cleaned. 2900 * 2901 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug. 2902 * 2903 * Possible hook names include: 2904 * 2905 * - `created_category` 2906 * - `created_post_tag` 2907 * 2908 * @since 2.3.0 2909 * @since 6.1.0 The `$args` parameter was added. 2910 * 2911 * @param int $term_id Term ID. 2912 * @param int $tt_id Term taxonomy ID. 2913 * @param array $args Arguments passed to wp_insert_term(). 2914 */ 2915 do_action( "created_{$taxonomy}", $term_id, $tt_id, $args ); 2916 2917 /** 2918 * Fires after a term has been saved, and the term cache has been cleared. 2919 * 2920 * The {@see 'saved_$taxonomy'} hook is also available for targeting a specific 2921 * taxonomy. 2922 * 2923 * @since 5.5.0 2924 * @since 6.1.0 The `$args` parameter was added. 2925 * 2926 * @param int $term_id Term ID. 2927 * @param int $tt_id Term taxonomy ID. 2928 * @param string $taxonomy Taxonomy slug. 2929 * @param bool $update Whether this is an existing term being updated. 2930 * @param array $args Arguments passed to wp_insert_term(). 2931 */ 2932 do_action( 'saved_term', $term_id, $tt_id, $taxonomy, false, $args ); 2933 2934 /** 2935 * Fires after a term in a specific taxonomy has been saved, and the term 2936 * cache has been cleared. 2937 * 2938 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug. 2939 * 2940 * Possible hook names include: 2941 * 2942 * - `saved_category` 2943 * - `saved_post_tag` 2944 * 2945 * @since 5.5.0 2946 * @since 6.1.0 The `$args` parameter was added. 2947 * 2948 * @param int $term_id Term ID. 2949 * @param int $tt_id Term taxonomy ID. 2950 * @param bool $update Whether this is an existing term being updated. 2951 * @param array $args Arguments passed to wp_insert_term(). 2952 */ 2953 do_action( "saved_{$taxonomy}", $term_id, $tt_id, false, $args ); 2954 2955 return array( 2956 'term_id' => $term_id, 2957 'term_taxonomy_id' => $tt_id, 2958 ); 2959 } 2960 2961 /** 2962 * Creates term and taxonomy relationships. 2963 * 2964 * Relates an object (post, link, etc.) to a term and taxonomy type. Creates the 2965 * term and taxonomy relationship if it doesn't already exist. Creates a term if 2966 * it doesn't exist (using the slug). 2967 * 2968 * A relationship means that the term is grouped in or belongs to the taxonomy. 2969 * A term has no meaning until it is given context by defining which taxonomy it 2970 * exists under. 2971 * 2972 * @since 2.3.0 2973 * 2974 * @global wpdb $wpdb WordPress database abstraction object. 2975 * 2976 * @param int $object_id The object to relate to. 2977 * @param string|int|array $terms A single term slug, single term ID, or array of either term slugs or IDs. 2978 * Will replace all existing related terms in this taxonomy. Passing an 2979 * empty array will remove all related terms. 2980 * @param string $taxonomy The context in which to relate the term to the object. 2981 * @param bool $append Optional. If false will delete difference of terms. Default false. 2982 * @return array|WP_Error Term taxonomy IDs of the affected terms or WP_Error on failure. 2983 */ 2984 function wp_set_object_terms( $object_id, $terms, $taxonomy, $append = false ) { 2985 global $wpdb; 2986 2987 $object_id = (int) $object_id; 2988 2989 if ( ! taxonomy_exists( $taxonomy ) ) { 2990 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); 2991 } 2992 2993 if ( empty( $terms ) ) { 2994 $terms = array(); 2995 } elseif ( ! is_array( $terms ) ) { 2996 $terms = array( $terms ); 2997 } 2998 2999 if ( ! $append ) { 3000 $old_tt_ids = wp_get_object_terms( 3001 $object_id, 3002 $taxonomy, 3003 array( 3004 'fields' => 'tt_ids', 3005 'orderby' => 'none', 3006 'update_term_meta_cache' => false, 3007 ) 3008 ); 3009 } else { 3010 $old_tt_ids = array(); 3011 } 3012 3013 $tt_ids = array(); 3014 $new_tt_ids = array(); 3015 3016 foreach ( (array) $terms as $term ) { 3017 if ( '' === trim( $term ) ) { 3018 continue; 3019 } 3020 3021 $term_info = term_exists( $term, $taxonomy ); 3022 3023 if ( ! $term_info ) { 3024 // Skip if a non-existent term ID is passed. 3025 if ( is_int( $term ) ) { 3026 continue; 3027 } 3028 3029 $term_info = wp_insert_term( $term, $taxonomy ); 3030 } 3031 3032 if ( is_wp_error( $term_info ) ) { 3033 return $term_info; 3034 } 3035 3036 $tt_id = $term_info['term_taxonomy_id']; 3037 $tt_ids[] = $tt_id; 3038 3039 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 ) ) ) { 3040 continue; 3041 } 3042 3043 /** 3044 * Fires immediately before an object-term relationship is added. 3045 * 3046 * @since 2.9.0 3047 * @since 4.7.0 Added the `$taxonomy` parameter. 3048 * 3049 * @param int $object_id Object ID. 3050 * @param int $tt_id Term taxonomy ID. 3051 * @param string $taxonomy Taxonomy slug. 3052 */ 3053 do_action( 'add_term_relationship', $object_id, $tt_id, $taxonomy ); 3054 3055 $wpdb->insert( 3056 $wpdb->term_relationships, 3057 array( 3058 'object_id' => $object_id, 3059 'term_taxonomy_id' => $tt_id, 3060 ) 3061 ); 3062 3063 /** 3064 * Fires immediately after an object-term relationship is added. 3065 * 3066 * @since 2.9.0 3067 * @since 4.7.0 Added the `$taxonomy` parameter. 3068 * 3069 * @param int $object_id Object ID. 3070 * @param int $tt_id Term taxonomy ID. 3071 * @param string $taxonomy Taxonomy slug. 3072 */ 3073 do_action( 'added_term_relationship', $object_id, $tt_id, $taxonomy ); 3074 3075 $new_tt_ids[] = $tt_id; 3076 } 3077 3078 if ( $new_tt_ids ) { 3079 wp_update_term_count( $new_tt_ids, $taxonomy ); 3080 } 3081 3082 if ( ! $append ) { 3083 $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids ); 3084 3085 if ( $delete_tt_ids ) { 3086 $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'"; 3087 $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 ) ); 3088 $delete_term_ids = array_map( 'intval', $delete_term_ids ); 3089 3090 $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy ); 3091 if ( is_wp_error( $remove ) ) { 3092 return $remove; 3093 } 3094 } 3095 } 3096 3097 $t = get_taxonomy( $taxonomy ); 3098 3099 if ( ! $append && isset( $t->sort ) && $t->sort ) { 3100 $values = array(); 3101 $term_order = 0; 3102 3103 $final_tt_ids = wp_get_object_terms( 3104 $object_id, 3105 $taxonomy, 3106 array( 3107 'fields' => 'tt_ids', 3108 'update_term_meta_cache' => false, 3109 ) 3110 ); 3111 3112 foreach ( $tt_ids as $tt_id ) { 3113 if ( in_array( (int) $tt_id, $final_tt_ids, true ) ) { 3114 $values[] = $wpdb->prepare( '(%d, %d, %d)', $object_id, $tt_id, ++$term_order ); 3115 } 3116 } 3117 3118 if ( $values ) { 3119 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)' ) ) { 3120 return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database.' ), $wpdb->last_error ); 3121 } 3122 } 3123 } 3124 3125 wp_cache_delete( $object_id, $taxonomy . '_relationships' ); 3126 wp_cache_set_terms_last_changed(); 3127 3128 /** 3129 * Fires after an object's terms have been set. 3130 * 3131 * @since 2.8.0 3132 * 3133 * @param int $object_id Object ID. 3134 * @param array $terms An array of object term IDs or slugs. 3135 * @param array $tt_ids An array of term taxonomy IDs. 3136 * @param string $taxonomy Taxonomy slug. 3137 * @param bool $append Whether to append new terms to the old terms. 3138 * @param array $old_tt_ids Old array of term taxonomy IDs. 3139 */ 3140 do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ); 3141 3142 return $tt_ids; 3143 } 3144 3145 /** 3146 * Adds term(s) associated with a given object. 3147 * 3148 * @since 3.6.0 3149 * 3150 * @param int $object_id The ID of the object to which the terms will be added. 3151 * @param string|int|array $terms The slug(s) or ID(s) of the term(s) to add. 3152 * @param array|string $taxonomy Taxonomy name. 3153 * @return array|WP_Error Term taxonomy IDs of the affected terms. 3154 */ 3155 function wp_add_object_terms( $object_id, $terms, $taxonomy ) { 3156 return wp_set_object_terms( $object_id, $terms, $taxonomy, true ); 3157 } 3158 3159 /** 3160 * Removes term(s) associated with a given object. 3161 * 3162 * @since 3.6.0 3163 * 3164 * @global wpdb $wpdb WordPress database abstraction object. 3165 * 3166 * @param int $object_id The ID of the object from which the terms will be removed. 3167 * @param string|int|array $terms The slug(s) or ID(s) of the term(s) to remove. 3168 * @param string $taxonomy Taxonomy name. 3169 * @return bool|WP_Error True on success, false or WP_Error on failure. 3170 */ 3171 function wp_remove_object_terms( $object_id, $terms, $taxonomy ) { 3172 global $wpdb; 3173 3174 $object_id = (int) $object_id; 3175 3176 if ( ! taxonomy_exists( $taxonomy ) ) { 3177 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); 3178 } 3179 3180 if ( ! is_array( $terms ) ) { 3181 $terms = array( $terms ); 3182 } 3183 3184 $tt_ids = array(); 3185 3186 foreach ( (array) $terms as $term ) { 3187 if ( '' === trim( $term ) ) { 3188 continue; 3189 } 3190 3191 $term_info = term_exists( $term, $taxonomy ); 3192 if ( ! $term_info ) { 3193 // Skip if a non-existent term ID is passed. 3194 if ( is_int( $term ) ) { 3195 continue; 3196 } 3197 } 3198 3199 if ( is_wp_error( $term_info ) ) { 3200 return $term_info; 3201 } 3202 3203 $tt_ids[] = $term_info['term_taxonomy_id']; 3204 } 3205 3206 if ( $tt_ids ) { 3207 $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'"; 3208 3209 /** 3210 * Fires immediately before an object-term relationship is deleted. 3211 * 3212 * @since 2.9.0 3213 * @since 4.7.0 Added the `$taxonomy` parameter. 3214 * 3215 * @param int $object_id Object ID. 3216 * @param array $tt_ids An array of term taxonomy IDs. 3217 * @param string $taxonomy Taxonomy slug. 3218 */ 3219 do_action( 'delete_term_relationships', $object_id, $tt_ids, $taxonomy ); 3220 3221 $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) ); 3222 3223 wp_cache_delete( $object_id, $taxonomy . '_relationships' ); 3224 wp_cache_set_terms_last_changed(); 3225 3226 /** 3227 * Fires immediately after an object-term relationship is deleted. 3228 * 3229 * @since 2.9.0 3230 * @since 4.7.0 Added the `$taxonomy` parameter. 3231 * 3232 * @param int $object_id Object ID. 3233 * @param array $tt_ids An array of term taxonomy IDs. 3234 * @param string $taxonomy Taxonomy slug. 3235 */ 3236 do_action( 'deleted_term_relationships', $object_id, $tt_ids, $taxonomy ); 3237 3238 wp_update_term_count( $tt_ids, $taxonomy ); 3239 3240 return (bool) $deleted; 3241 } 3242 3243 return false; 3244 } 3245 3246 /** 3247 * Makes term slug unique, if it isn't already. 3248 * 3249 * The `$slug` has to be unique global to every taxonomy, meaning that one 3250 * taxonomy term can't have a matching slug with another taxonomy term. Each 3251 * slug has to be globally unique for every taxonomy. 3252 * 3253 * The way this works is that if the taxonomy that the term belongs to is 3254 * hierarchical and has a parent, it will append that parent to the $slug. 3255 * 3256 * If that still doesn't return a unique slug, then it tries to append a number 3257 * until it finds a number that is truly unique. 3258 * 3259 * Appending a parent slug or a number can push the result past the 200 character 3260 * limit of the `slug` column in the terms table, so the slug is truncated to make 3261 * room for whatever is appended to it. 3262 * 3263 * The only purpose for `$term` is for appending a parent, if one exists. 3264 * 3265 * @since 2.3.0 3266 * @since 7.2.0 The returned slug is truncated to 200 characters when a parent slug 3267 * or a numeric suffix is appended to it. 3268 * 3269 * @global wpdb $wpdb WordPress database abstraction object. 3270 * 3271 * @param string $slug The string that will be tried for a unique slug. 3272 * @param object $term The term object that the `$slug` will belong to. 3273 * @return string Will return a true unique slug. 3274 * 3275 * @phpstan-param object{ taxonomy: string, parent?: int, term_id?: int } $term 3276 */ 3277 function wp_unique_term_slug( $slug, $term ) { 3278 global $wpdb; 3279 3280 $needs_suffix = true; 3281 $original_slug = $slug; 3282 3283 // As of 4.1, duplicate slugs are allowed as long as they're in different taxonomies. 3284 if ( ! term_exists( $slug ) || get_option( 'db_version' ) >= 30133 && ! get_term_by( 'slug', $slug, $term->taxonomy ) ) { 3285 $needs_suffix = false; 3286 } 3287 3288 /* 3289 * If the taxonomy supports hierarchy and the term has a parent, make the slug unique 3290 * by incorporating parent slugs. 3291 */ 3292 $parent_suffix = ''; 3293 if ( $needs_suffix && is_taxonomy_hierarchical( $term->taxonomy ) && ! empty( $term->parent ) ) { 3294 $the_parent = $term->parent; 3295 do { 3296 $parent_term = get_term( $the_parent, $term->taxonomy ); 3297 if ( is_wp_error( $parent_term ) || empty( $parent_term ) ) { 3298 break; 3299 } 3300 $parent_suffix .= '-' . $parent_term->slug; 3301 if ( ! term_exists( $slug . $parent_suffix ) ) { 3302 break; 3303 } 3304 3305 $the_parent = $parent_term->parent; 3306 } while ( ! empty( $the_parent ) ); 3307 } 3308 3309 // If we didn't get a unique slug, try appending a number to make it unique. 3310 3311 /** 3312 * Filters whether the proposed unique term slug is bad. 3313 * 3314 * @since 4.3.0 3315 * 3316 * @param bool $needs_suffix Whether the slug needs to be made unique with a suffix. 3317 * @param string $slug The slug. 3318 * @param object $term Term object. 3319 */ 3320 if ( apply_filters( 'wp_unique_term_slug_is_bad_slug', $needs_suffix, $slug, $term ) ) { 3321 if ( $parent_suffix ) { 3322 $slug = wp_truncate_slug( $slug . $parent_suffix, 200 ); 3323 } 3324 3325 if ( ! empty( $term->term_id ) ) { 3326 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id ); 3327 } else { 3328 $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug ); 3329 } 3330 3331 if ( $wpdb->get_var( $query ) ) { // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 3332 $num = 2; 3333 do { 3334 // Reserve room for the suffix so the result still fits the 200 character column. 3335 $numeric_suffix = "-$num"; 3336 $alt_slug = wp_truncate_slug( $slug, 200 - strlen( $numeric_suffix ) ) . $numeric_suffix; 3337 ++$num; 3338 $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) ); 3339 } while ( $slug_check ); 3340 $slug = $alt_slug; 3341 } 3342 } 3343 3344 /** 3345 * Filters the unique term slug. 3346 * 3347 * @since 4.3.0 3348 * 3349 * @param string $slug Unique term slug. 3350 * @param object $term Term object. 3351 * @param string $original_slug Slug originally passed to the function for testing. 3352 */ 3353 return apply_filters( 'wp_unique_term_slug', $slug, $term, $original_slug ); 3354 } 3355 3356 /** 3357 * Updates term based on arguments provided. 3358 * 3359 * The `$args` will indiscriminately override all values with the same field name. 3360 * Care must be taken to not override important information need to update or 3361 * update will fail (or perhaps create a new term, neither would be acceptable). 3362 * 3363 * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not 3364 * defined in `$args` already. 3365 * 3366 * 'alias_of' will create a term group, if it doesn't already exist, and 3367 * update it for the `$term`. 3368 * 3369 * If the 'slug' argument in `$args` is missing, then the 'name' will be used. 3370 * If you set 'slug' and it isn't unique, then a WP_Error is returned. 3371 * If you don't pass any slug, then a unique one will be created. 3372 * 3373 * @since 2.3.0 3374 * 3375 * @global wpdb $wpdb WordPress database abstraction object. 3376 * 3377 * @param int $term_id The ID of the term. 3378 * @param string $taxonomy The taxonomy of the term. 3379 * @param array $args { 3380 * Optional. Array of arguments for updating a term. 3381 * 3382 * @type string $alias_of Slug of the term to make this term an alias of. 3383 * Default empty string. Accepts a term slug. 3384 * @type string $description The term description. Default empty string. 3385 * @type int $parent The id of the parent term. Default 0. 3386 * @type string $slug The term slug to use. Default empty string. 3387 * } 3388 * @return array|WP_Error An array containing the `term_id` and `term_taxonomy_id`, 3389 * WP_Error otherwise. 3390 * @phpstan-param array{ 3391 * alias_of?: string, 3392 * description?: string, 3393 * parent?: non-negative-int, 3394 * slug?: string|null, 3395 * ... 3396 * } $args 3397 * @phpstan-return array{ 3398 * term_id: non-negative-int, 3399 * term_taxonomy_id: int, 3400 * }|WP_Error 3401 */ 3402 function wp_update_term( $term_id, $taxonomy, $args = array() ) { 3403 global $wpdb; 3404 3405 if ( ! taxonomy_exists( $taxonomy ) ) { 3406 return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); 3407 } 3408 3409 $term_id = (int) $term_id; 3410 3411 // First, get all of the original args. 3412 $term = get_term( $term_id, $taxonomy ); 3413 3414 if ( is_wp_error( $term ) ) { 3415 return $term; 3416 } 3417 3418 if ( ! $term ) { 3419 return new WP_Error( 'invalid_term', __( 'Empty Term.' ) ); 3420 } 3421 3422 $term = (array) $term->data; 3423 3424 // Escape data pulled from DB. 3425 $term = wp_slash( $term ); 3426 3427 // Merge old and new args with new args overwriting old ones. 3428 $args = array_merge( $term, $args ); 3429 3430 $defaults = array( 3431 'alias_of' => '', 3432 'description' => '', 3433 'parent' => 0, 3434 'slug' => '', 3435 ); 3436 $args = wp_parse_args( $args, $defaults ); 3437 $args = sanitize_term( $args, $taxonomy, 'db' ); 3438 $parsed_args = $args; 3439 3440 // expected_slashed ($name) 3441 $name = wp_unslash( $args['name'] ); 3442 $description = wp_unslash( $args['description'] ); 3443 3444 $parsed_args['name'] = $name; 3445 $parsed_args['description'] = $description; 3446 3447 if ( '' === trim( $name ) ) { 3448 return new WP_Error( 'empty_term_name', __( 'A name is required for this term.' ) ); 3449 } 3450 3451 if ( (int) $parsed_args['parent'] > 0 && ! term_exists( (int) $parsed_args['parent'] ) ) { 3452 return new WP_Error( 'missing_parent', __( 'Parent term does not exist.' ) ); 3453 } 3454 3455 $empty_slug = false; 3456 if ( empty( $args['slug'] ) ) { 3457 $empty_slug = true; 3458 $slug = sanitize_title( $name ); 3459 } else { 3460 $slug = $args['slug']; 3461 } 3462 3463 $parsed_args['slug'] = $slug; 3464 3465 $term_group = $parsed_args['term_group'] ?? 0; 3466 if ( $args['alias_of'] ) { 3467 $alias = get_term_by( 'slug', $args['alias_of'], $taxonomy ); 3468 if ( ! empty( $alias->term_group ) ) { 3469 // The alias we want is already in a group, so let's use that one. 3470 $term_group = $alias->term_group; 3471 } elseif ( ! empty( $alias->term_id ) ) { 3472 /* 3473 * The alias is not in a group, so we create a new one 3474 * and add the alias to it. 3475 */ 3476 $term_group = $wpdb->get_var( "SELECT MAX(term_group) FROM $wpdb->terms" ) + 1; 3477 3478 wp_update_term( 3479 $alias->term_id, 3480 $taxonomy, 3481 array( 3482 'term_group' => $term_group, 3483 ) 3484 ); 3485 } 3486 3487 $parsed_args['term_group'] = $term_group; 3488 } 3489 3490 /** 3491 * Filters the term parent. 3492 * 3493 * Hook to this filter to see if it will cause a hierarchy loop. 3494 * 3495 * @since 3.1.0 3496 * 3497 * @param int $parent_term ID of the parent term. 3498 * @param int $term_id Term ID. 3499 * @param string $taxonomy Taxonomy slug. 3500 * @param array $parsed_args An array of potentially altered update arguments for the given term. 3501 * @param array $args Arguments passed to wp_update_term(). 3502 */ 3503 $parent = (int) apply_filters( 'wp_update_term_parent', $args['parent'], $term_id, $taxonomy, $parsed_args, $args ); 3504 3505 // Check for duplicate slug. 3506 $duplicate = get_term_by( 'slug', $slug, $taxonomy ); 3507 if ( $duplicate && $duplicate->term_id !== $term_id ) { 3508 /* 3509 * If an empty slug was passed or the parent changed, reset the slug to something unique. 3510 * Otherwise, bail. 3511 */ 3512 if ( $empty_slug || ( $parent !== (int) $term['parent'] ) ) { 3513 $slug = wp_unique_term_slug( $slug, (object) $args ); 3514 } else { 3515 /* translators: %s: Taxonomy term slug. */ 3516 return new WP_Error( 'duplicate_term_slug', sprintf( __( 'The slug “%s” is already in use by another term.' ), $slug ) ); 3517 } 3518 } 3519 3520 $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 ) ); 3521 3522 // Check whether this is a shared term that needs splitting. 3523 $_term_id = _split_shared_term( $term_id, $tt_id ); 3524 if ( ! is_wp_error( $_term_id ) ) { 3525 $term_id = $_term_id; 3526 } 3527 3528 /** 3529 * Fires immediately before the given terms are edited. 3530 * 3531 * @since 2.9.0 3532 * @since 6.1.0 The `$args` parameter was added. 3533 * 3534 * @param int $term_id Term ID. 3535 * @param string $taxonomy Taxonomy slug. 3536 * @param array $args Arguments passed to wp_update_term(). 3537 */ 3538 do_action( 'edit_terms', $term_id, $taxonomy, $args ); 3539 3540 $data = compact( 'name', 'slug', 'term_group' ); 3541 3542 /** 3543 * Filters term data before it is updated in the database. 3544 * 3545 * @since 4.7.0 3546 * 3547 * @param array $data Term data to be updated. 3548 * @param int $term_id Term ID. 3549 * @param string $taxonomy Taxonomy slug. 3550 * @param array $args Arguments passed to wp_update_term(). 3551 */ 3552 $data = apply_filters( 'wp_update_term_data', $data, $term_id, $taxonomy, $args ); 3553 3554 $wpdb->update( $wpdb->terms, $data, compact( 'term_id' ) ); 3555 3556 if ( empty( $slug ) ) { 3557 $slug = sanitize_title( $name, $term_id ); 3558 $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) ); 3559 } 3560 3561 /** 3562 * Fires immediately after a term is updated in the database, but before its 3563 * term-taxonomy relationship is updated. 3564 * 3565 * @since 2.9.0 3566 * @since 6.1.0 The `$args` parameter was added. 3567 * 3568 * @param int $term_id Term ID. 3569 * @param string $taxonomy Taxonomy slug. 3570 * @param array $args Arguments passed to wp_update_term(). 3571 */ 3572 do_action( 'edited_terms', $term_id, $taxonomy, $args ); 3573 3574 /** 3575 * Fires immediate before a term-taxonomy relationship is updated. 3576 * 3577 * @since 2.9.0 3578 * @since 6.1.0 The `$args` parameter was added. 3579 * 3580 * @param int $tt_id Term taxonomy ID. 3581 * @param string $taxonomy Taxonomy slug. 3582 * @param array $args Arguments passed to wp_update_term(). 3583 */ 3584 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy, $args ); 3585 3586 $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) ); 3587 3588 /** 3589 * Fires immediately after a term-taxonomy relationship is updated. 3590 * 3591 * @since 2.9.0 3592 * @since 6.1.0 The `$args` parameter was added. 3593 * 3594 * @param int $tt_id Term taxonomy ID. 3595 * @param string $taxonomy Taxonomy slug. 3596 * @param array $args Arguments passed to wp_update_term(). 3597 */ 3598 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy, $args ); 3599 3600 /** 3601 * Fires after a term has been updated, but before the term cache has been cleaned. 3602 * 3603 * The {@see 'edit_$taxonomy'} hook is also available for targeting a specific 3604 * taxonomy. 3605 * 3606 * @since 2.3.0 3607 * @since 6.1.0 The `$args` parameter was added. 3608 * 3609 * @param int $term_id Term ID. 3610 * @param int $tt_id Term taxonomy ID. 3611 * @param string $taxonomy Taxonomy slug. 3612 * @param array $args Arguments passed to wp_update_term(). 3613 */ 3614 do_action( 'edit_term', $term_id, $tt_id, $taxonomy, $args ); 3615 3616 /** 3617 * Fires after a term in a specific taxonomy has been updated, but before the term 3618 * cache has been cleaned. 3619 * 3620 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug. 3621 * 3622 * Possible hook names include: 3623 * 3624 * - `edit_category` 3625 * - `edit_post_tag` 3626 * 3627 * @since 2.3.0 3628 * @since 6.1.0 The `$args` parameter was added. 3629 * 3630 * @param int $term_id Term ID. 3631 * @param int $tt_id Term taxonomy ID. 3632 * @param array $args Arguments passed to wp_update_term(). 3633 */ 3634 do_action( "edit_{$taxonomy}", $term_id, $tt_id, $args ); 3635 3636 /** This filter is documented in wp-includes/taxonomy.php */ 3637 $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id, $args ); 3638 3639 clean_term_cache( $term_id, $taxonomy ); 3640 3641 /** 3642 * Fires after a term has been updated, and the term cache has been cleaned. 3643 * 3644 * The {@see 'edited_$taxonomy'} hook is also available for targeting a specific 3645 * taxonomy. 3646 * 3647 * @since 2.3.0 3648 * @since 6.1.0 The `$args` parameter was added. 3649 * 3650 * @param int $term_id Term ID. 3651 * @param int $tt_id Term taxonomy ID. 3652 * @param string $taxonomy Taxonomy slug. 3653 * @param array $args Arguments passed to wp_update_term(). 3654 */ 3655 do_action( 'edited_term', $term_id, $tt_id, $taxonomy, $args ); 3656 3657 /** 3658 * Fires after a term for a specific taxonomy has been updated, and the term 3659 * cache has been cleaned. 3660 * 3661 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug. 3662 * 3663 * Possible hook names include: 3664 * 3665 * - `edited_category` 3666 * - `edited_post_tag` 3667 * 3668 * @since 2.3.0 3669 * @since 6.1.0 The `$args` parameter was added. 3670 * 3671 * @param int $term_id Term ID. 3672 * @param int $tt_id Term taxonomy ID. 3673 * @param array $args Arguments passed to wp_update_term(). 3674 */ 3675 do_action( "edited_{$taxonomy}", $term_id, $tt_id, $args ); 3676 3677 /** This action is documented in wp-includes/taxonomy.php */ 3678 do_action( 'saved_term', $term_id, $tt_id, $taxonomy, true, $args ); 3679 3680 /** This action is documented in wp-includes/taxonomy.php */ 3681 do_action( "saved_{$taxonomy}", $term_id, $tt_id, true, $args ); 3682 3683 return array( 3684 'term_id' => $term_id, 3685 'term_taxonomy_id' => $tt_id, 3686 ); 3687 } 3688 3689 /** 3690 * Enables or disables term counting. 3691 * 3692 * @since 2.5.0 3693 * 3694 * @param bool $defer Optional. Enable if true, disable if false. 3695 * @return bool Whether term counting is enabled or disabled. 3696 */ 3697 function wp_defer_term_counting( $defer = null ) { 3698 static $_defer = false; 3699 3700 if ( is_bool( $defer ) ) { 3701 $_defer = $defer; 3702 // Flush any deferred counts. 3703 if ( ! $defer ) { 3704 wp_update_term_count( null, null, true ); 3705 } 3706 } 3707 3708 return $_defer; 3709 } 3710 3711 /** 3712 * Updates the amount of terms in taxonomy. 3713 * 3714 * If there is a taxonomy callback applied, then it will be called for updating 3715 * the count. 3716 * 3717 * The default action is to count what the amount of terms have the relationship 3718 * of term ID. Once that is done, then update the database. 3719 * 3720 * @since 2.3.0 3721 * 3722 * @param int|array $terms The term_taxonomy_id of the terms. 3723 * @param string $taxonomy The context of the term. 3724 * @param bool $do_deferred Whether to flush the deferred term counts too. Default false. 3725 * @return bool If no terms will return false, and if successful will return true. 3726 */ 3727 function wp_update_term_count( $terms, $taxonomy, $do_deferred = false ) { 3728 static $_deferred = array(); 3729 3730 if ( $do_deferred ) { 3731 foreach ( (array) array_keys( $_deferred ) as $tax ) { 3732 wp_update_term_count_now( $_deferred[ $tax ], $tax ); 3733 unset( $_deferred[ $tax ] ); 3734 } 3735 } 3736 3737 if ( empty( $terms ) ) { 3738 return false; 3739 } 3740 3741 if ( ! is_array( $terms ) ) { 3742 $terms = array( $terms ); 3743 } 3744 3745 if ( wp_defer_term_counting() ) { 3746 $_deferred[ $taxonomy ] = array_unique( array_merge( $_deferred[ $taxonomy ] ?? array(), $terms ) ); 3747 return true; 3748 } 3749 3750 return wp_update_term_count_now( $terms, $taxonomy ); 3751 } 3752 3753 /** 3754 * Performs term count update immediately. 3755 * 3756 * @since 2.5.0 3757 * 3758 * @param array $terms The term_taxonomy_id of terms to update. 3759 * @param string $taxonomy The context of the term. 3760 * @return true Always true when complete. 3761 */ 3762 function wp_update_term_count_now( $terms, $taxonomy ) { 3763 $terms = array_map( 'intval', $terms ); 3764 3765 $taxonomy = get_taxonomy( $taxonomy ); 3766 if ( ! empty( $taxonomy->update_count_callback ) ) { 3767 call_user_func( $taxonomy->update_count_callback, $terms, $taxonomy ); 3768 } else { 3769 $object_types = (array) $taxonomy->object_type; 3770 foreach ( $object_types as &$object_type ) { 3771 if ( str_starts_with( $object_type, 'attachment:' ) ) { 3772 list( $object_type ) = explode( ':', $object_type ); 3773 } 3774 } 3775 3776 if ( array_filter( $object_types, 'post_type_exists' ) == $object_types ) { 3777 // Only post types are attached to this taxonomy. 3778 _update_post_term_count( $terms, $taxonomy ); 3779 } else { 3780 // Default count updater. 3781 _update_generic_term_count( $terms, $taxonomy ); 3782 } 3783 } 3784 3785 clean_term_cache( $terms, '', false ); 3786 3787 return true; 3788 } 3789 3790 // 3791 // Cache. 3792 // 3793 3794 /** 3795 * Removes the taxonomy relationship to terms from the cache. 3796 * 3797 * Will remove the entire taxonomy relationship containing term `$object_id`. The 3798 * term IDs have to exist within the taxonomy `$object_type` for the deletion to 3799 * take place. 3800 * 3801 * @since 2.3.0 3802 * 3803 * @see get_object_taxonomies() for more on $object_type. 3804 * 3805 * @global bool $_wp_suspend_cache_invalidation. 3806 * 3807 * @param int|array $object_ids Single or list of term object ID(s). 3808 * @param array|string $object_type The taxonomy object type. 3809 */ 3810 function clean_object_term_cache( $object_ids, $object_type ) { 3811 global $_wp_suspend_cache_invalidation; 3812 3813 if ( ! empty( $_wp_suspend_cache_invalidation ) ) { 3814 return; 3815 } 3816 3817 if ( ! is_array( $object_ids ) ) { 3818 $object_ids = array( $object_ids ); 3819 } 3820 3821 $taxonomies = get_object_taxonomies( $object_type ); 3822 3823 foreach ( $taxonomies as $taxonomy ) { 3824 wp_cache_delete_multiple( $object_ids, "{$taxonomy}_relationships" ); 3825 } 3826 3827 wp_cache_set_terms_last_changed(); 3828 3829 /** 3830 * Fires after the object term cache has been cleaned. 3831 * 3832 * @since 2.5.0 3833 * 3834 * @param array $object_ids An array of object IDs. 3835 * @param string $object_type Object type. 3836 */ 3837 do_action( 'clean_object_term_cache', $object_ids, $object_type ); 3838 } 3839 3840 /** 3841 * Removes all of the term IDs from the cache. 3842 * 3843 * @since 2.3.0 3844 * 3845 * @global wpdb $wpdb WordPress database abstraction object. 3846 * @global bool $_wp_suspend_cache_invalidation 3847 * 3848 * @param int|int[] $ids Single or array of term IDs. 3849 * @param string $taxonomy Optional. Taxonomy slug. Can be empty, in which case the taxonomies of the passed 3850 * term IDs will be used. Default empty. 3851 * @param bool $clean_taxonomy Optional. Whether to clean taxonomy wide caches (true), or just individual 3852 * term object caches (false). Default true. 3853 */ 3854 function clean_term_cache( $ids, $taxonomy = '', $clean_taxonomy = true ) { 3855 global $wpdb, $_wp_suspend_cache_invalidation; 3856 3857 if ( ! empty( $_wp_suspend_cache_invalidation ) ) { 3858 return; 3859 } 3860 3861 if ( ! is_array( $ids ) ) { 3862 $ids = array( $ids ); 3863 } 3864 3865 $taxonomies = array(); 3866 // If no taxonomy, assume tt_ids. 3867 if ( empty( $taxonomy ) ) { 3868 $tt_ids = array_map( 'intval', $ids ); 3869 $tt_ids = implode( ', ', $tt_ids ); 3870 $terms = $wpdb->get_results( "SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)" ); 3871 $ids = array(); 3872 3873 foreach ( (array) $terms as $term ) { 3874 $taxonomies[] = $term->taxonomy; 3875 $ids[] = $term->term_id; 3876 } 3877 wp_cache_delete_multiple( $ids, 'terms' ); 3878 $taxonomies = array_unique( $taxonomies ); 3879 } else { 3880 wp_cache_delete_multiple( $ids, 'terms' ); 3881 $taxonomies = array( $taxonomy ); 3882 } 3883 3884 foreach ( $taxonomies as $taxonomy ) { 3885 if ( $clean_taxonomy ) { 3886 clean_taxonomy_cache( $taxonomy ); 3887 } 3888 3889 /** 3890 * Fires once after each taxonomy's term cache has been cleaned. 3891 * 3892 * @since 2.5.0 3893 * @since 4.5.0 Added the `$clean_taxonomy` parameter. 3894 * 3895 * @param array $ids An array of term IDs. 3896 * @param string $taxonomy Taxonomy slug. 3897 * @param bool $clean_taxonomy Whether or not to clean taxonomy-wide caches 3898 */ 3899 do_action( 'clean_term_cache', $ids, $taxonomy, $clean_taxonomy ); 3900 } 3901 3902 wp_cache_set_terms_last_changed(); 3903 } 3904 3905 /** 3906 * Cleans the caches for a taxonomy. 3907 * 3908 * @since 4.9.0 3909 * 3910 * @param string $taxonomy Taxonomy slug. 3911 */ 3912 function clean_taxonomy_cache( $taxonomy ) { 3913 wp_cache_delete( 'all_ids', $taxonomy ); 3914 wp_cache_delete( 'get', $taxonomy ); 3915 wp_cache_set_terms_last_changed(); 3916 3917 // Regenerate cached hierarchy. 3918 if ( is_taxonomy_hierarchical( $taxonomy ) ) { 3919 delete_option( "{$taxonomy}_children" ); 3920 _get_term_hierarchy( $taxonomy ); 3921 } 3922 3923 /** 3924 * Fires after a taxonomy's caches have been cleaned. 3925 * 3926 * @since 4.9.0 3927 * 3928 * @param string $taxonomy Taxonomy slug. 3929 */ 3930 do_action( 'clean_taxonomy_cache', $taxonomy ); 3931 } 3932 3933 /** 3934 * Retrieves the cached term objects for the given object ID. 3935 * 3936 * Upstream functions (like get_the_terms() and is_object_in_term()) are 3937 * responsible for populating the object-term relationship cache. The current 3938 * function only fetches relationship data that is already in the cache. 3939 * 3940 * @since 2.3.0 3941 * @since 4.7.0 Returns a `WP_Error` object if there's an error with 3942 * any of the matched terms. 3943 * 3944 * @param int $id Term object ID, for example a post, comment, or user ID. 3945 * @param string $taxonomy Taxonomy name. 3946 * @return bool|WP_Term[]|WP_Error Array of `WP_Term` objects, if cached. 3947 * False if cache is empty for `$taxonomy` and `$id`. 3948 * WP_Error if get_term() returns an error object for any term. 3949 */ 3950 function get_object_term_cache( $id, $taxonomy ) { 3951 $_term_ids = wp_cache_get( $id, "{$taxonomy}_relationships" ); 3952 3953 // We leave the priming of relationship caches to upstream functions. 3954 if ( false === $_term_ids ) { 3955 return false; 3956 } 3957 3958 // Backward compatibility for if a plugin is putting objects into the cache, rather than IDs. 3959 $term_ids = array(); 3960 foreach ( $_term_ids as $term_id ) { 3961 if ( is_numeric( $term_id ) ) { 3962 $term_ids[] = (int) $term_id; 3963 } elseif ( isset( $term_id->term_id ) ) { 3964 $term_ids[] = (int) $term_id->term_id; 3965 } 3966 } 3967 3968 // Fill the term objects. 3969 _prime_term_caches( $term_ids ); 3970 3971 $terms = array(); 3972 foreach ( $term_ids as $term_id ) { 3973 $term = get_term( $term_id, $taxonomy ); 3974 if ( is_wp_error( $term ) ) { 3975 return $term; 3976 } 3977 3978 $terms[] = $term; 3979 } 3980 3981 return $terms; 3982 } 3983 3984 /** 3985 * Updates the cache for the given term object ID(s). 3986 * 3987 * Note: Due to performance concerns, great care should be taken to only update 3988 * term caches when necessary. Processing time can increase exponentially depending 3989 * on both the number of passed term IDs and the number of taxonomies those terms 3990 * belong to. 3991 * 3992 * Caches will only be updated for terms not already cached. 3993 * 3994 * @since 2.3.0 3995 * 3996 * @param string|int[] $object_ids Comma-separated list or array of term object IDs. 3997 * @param string|string[] $object_type The taxonomy object type or array of the same. 3998 * @return void|false Void on success or if the `$object_ids` parameter is empty, 3999 * false if all of the terms in `$object_ids` are already cached. 4000 */ 4001 function update_object_term_cache( $object_ids, $object_type ) { 4002 if ( empty( $object_ids ) ) { 4003 return; 4004 } 4005 4006 if ( ! is_array( $object_ids ) ) { 4007 $object_ids = explode( ',', $object_ids ); 4008 } 4009 4010 $object_ids = array_map( 'intval', $object_ids ); 4011 $non_cached_ids = array(); 4012 4013 $taxonomies = get_object_taxonomies( $object_type ); 4014 4015 foreach ( $taxonomies as $taxonomy ) { 4016 $cache_values = wp_cache_get_multiple( (array) $object_ids, "{$taxonomy}_relationships" ); 4017 4018 foreach ( $cache_values as $id => $value ) { 4019 if ( false === $value ) { 4020 $non_cached_ids[] = $id; 4021 } 4022 } 4023 } 4024 4025 if ( empty( $non_cached_ids ) ) { 4026 return false; 4027 } 4028 4029 $non_cached_ids = array_unique( $non_cached_ids ); 4030 4031 $terms = wp_get_object_terms( 4032 $non_cached_ids, 4033 $taxonomies, 4034 array( 4035 'fields' => 'all_with_object_id', 4036 'orderby' => 'name', 4037 'update_term_meta_cache' => false, 4038 ) 4039 ); 4040 4041 $object_terms = array(); 4042 foreach ( (array) $terms as $term ) { 4043 $object_terms[ $term->object_id ][ $term->taxonomy ][] = $term->term_id; 4044 } 4045 4046 foreach ( $non_cached_ids as $id ) { 4047 foreach ( $taxonomies as $taxonomy ) { 4048 if ( ! isset( $object_terms[ $id ][ $taxonomy ] ) ) { 4049 $object_terms[ $id ][ $taxonomy ] = array(); 4050 } 4051 } 4052 } 4053 4054 $cache_values = array(); 4055 foreach ( $object_terms as $id => $value ) { 4056 foreach ( $value as $taxonomy => $terms ) { 4057 $cache_values[ $taxonomy ][ $id ] = $terms; 4058 } 4059 } 4060 foreach ( $cache_values as $taxonomy => $data ) { 4061 wp_cache_add_multiple( $data, "{$taxonomy}_relationships" ); 4062 } 4063 } 4064 4065 /** 4066 * Updates terms in cache. 4067 * 4068 * @since 2.3.0 4069 * 4070 * @param WP_Term[] $terms Array of term objects to change. 4071 * @param string $taxonomy Not used. 4072 */ 4073 function update_term_cache( $terms, $taxonomy = '' ) { 4074 $data = array(); 4075 foreach ( (array) $terms as $term ) { 4076 // Create a copy in case the array was passed by reference. 4077 $_term = clone $term; 4078 4079 // Object ID should not be cached. 4080 unset( $_term->object_id ); 4081 4082 $data[ $term->term_id ] = $_term; 4083 } 4084 wp_cache_add_multiple( $data, 'terms' ); 4085 } 4086 4087 // 4088 // Private. 4089 // 4090 4091 /** 4092 * Retrieves children of taxonomy as term IDs. 4093 * 4094 * @access private 4095 * @since 2.3.0 4096 * 4097 * @param string $taxonomy Taxonomy name. 4098 * @return array Empty if $taxonomy isn't hierarchical or returns children as term IDs. 4099 */ 4100 function _get_term_hierarchy( $taxonomy ) { 4101 if ( ! is_taxonomy_hierarchical( $taxonomy ) ) { 4102 return array(); 4103 } 4104 $children = get_option( "{$taxonomy}_children" ); 4105 4106 if ( is_array( $children ) ) { 4107 return $children; 4108 } 4109 $children = array(); 4110 $terms = get_terms( 4111 array( 4112 'taxonomy' => $taxonomy, 4113 'get' => 'all', 4114 'orderby' => 'id', 4115 'fields' => 'id=>parent', 4116 'update_term_meta_cache' => false, 4117 ) 4118 ); 4119 foreach ( $terms as $term_id => $parent ) { 4120 if ( $parent > 0 ) { 4121 $children[ $parent ][] = $term_id; 4122 } 4123 } 4124 update_option( "{$taxonomy}_children", $children ); 4125 4126 return $children; 4127 } 4128 4129 /** 4130 * Gets the subset of $terms that are descendants of $term_id. 4131 * 4132 * If `$terms` is an array of objects, then _get_term_children() returns an array of objects. 4133 * If `$terms` is an array of IDs, then _get_term_children() returns an array of IDs. 4134 * 4135 * @access private 4136 * @since 2.3.0 4137 * 4138 * @param int $term_id The ancestor term: all returned terms should be descendants of `$term_id`. 4139 * @param array $terms The set of terms - either an array of term objects or term IDs - from which those that 4140 * are descendants of $term_id will be chosen. 4141 * @param string $taxonomy The taxonomy which determines the hierarchy of the terms. 4142 * @param array $ancestors Optional. Term ancestors that have already been identified. Passed by reference, to keep 4143 * track of found terms when recursing the hierarchy. The array of located ancestors is used 4144 * to prevent infinite recursion loops. For performance, `term_ids` are used as array keys, 4145 * with 1 as value. Default empty array. 4146 * @return array|WP_Error The subset of $terms that are descendants of $term_id. 4147 */ 4148 function _get_term_children( $term_id, $terms, $taxonomy, &$ancestors = array() ) { 4149 $empty_array = array(); 4150 if ( empty( $terms ) ) { 4151 return $empty_array; 4152 } 4153 4154 $term_id = (int) $term_id; 4155 $term_list = array(); 4156 $has_children = _get_term_hierarchy( $taxonomy ); 4157 4158 if ( $term_id && ! isset( $has_children[ $term_id ] ) ) { 4159 return $empty_array; 4160 } 4161 4162 // Include the term itself in the ancestors array, so we can properly detect when a loop has occurred. 4163 if ( empty( $ancestors ) ) { 4164 $ancestors[ $term_id ] = 1; 4165 } 4166 4167 foreach ( (array) $terms as $term ) { 4168 $use_id = false; 4169 if ( ! is_object( $term ) ) { 4170 $term = get_term( $term, $taxonomy ); 4171 if ( is_wp_error( $term ) ) { 4172 return $term; 4173 } 4174 $use_id = true; 4175 } 4176 4177 // Don't recurse if we've already identified the term as a child - this indicates a loop. 4178 if ( isset( $ancestors[ $term->term_id ] ) ) { 4179 continue; 4180 } 4181 4182 if ( (int) $term->parent === $term_id ) { 4183 if ( $use_id ) { 4184 $term_list[] = $term->term_id; 4185 } else { 4186 $term_list[] = $term; 4187 } 4188 4189 if ( ! isset( $has_children[ $term->term_id ] ) ) { 4190 continue; 4191 } 4192 4193 $ancestors[ $term->term_id ] = 1; 4194 4195 $children = _get_term_children( $term->term_id, $terms, $taxonomy, $ancestors ); 4196 if ( $children ) { 4197 $term_list = array_merge( $term_list, $children ); 4198 } 4199 } 4200 } 4201 4202 return $term_list; 4203 } 4204 4205 /** 4206 * Adds count of children to parent count. 4207 * 4208 * Recalculates term counts by including items from child terms. Assumes all 4209 * relevant children are already in the $terms argument. 4210 * 4211 * @access private 4212 * @since 2.3.0 4213 * 4214 * @global wpdb $wpdb WordPress database abstraction object. 4215 * 4216 * @param object[]|WP_Term[] $terms List of term objects (passed by reference). 4217 * @param string $taxonomy Term context. 4218 */ 4219 function _pad_term_counts( &$terms, $taxonomy ) { 4220 global $wpdb; 4221 4222 // This function only works for hierarchical taxonomies like post categories. 4223 if ( ! is_taxonomy_hierarchical( $taxonomy ) ) { 4224 return; 4225 } 4226 4227 $term_hier = _get_term_hierarchy( $taxonomy ); 4228 4229 if ( empty( $term_hier ) ) { 4230 return; 4231 } 4232 4233 $term_items = array(); 4234 $terms_by_id = array(); 4235 $term_ids = array(); 4236 4237 foreach ( (array) $terms as $key => $term ) { 4238 $terms_by_id[ $term->term_id ] = & $terms[ $key ]; 4239 $term_ids[ $term->term_taxonomy_id ] = $term->term_id; 4240 } 4241 4242 // Get the object and term IDs and stick them in a lookup table. 4243 $tax_obj = get_taxonomy( $taxonomy ); 4244 $object_types = esc_sql( $tax_obj->object_type ); 4245 $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'" ); 4246 4247 foreach ( $results as $row ) { 4248 $id = $term_ids[ $row->term_taxonomy_id ]; 4249 4250 $term_items[ $id ][ $row->object_id ] = isset( $term_items[ $id ][ $row->object_id ] ) ? ++$term_items[ $id ][ $row->object_id ] : 1; 4251 } 4252 4253 // Touch every ancestor's lookup row for each post in each term. 4254 foreach ( $term_ids as $term_id ) { 4255 $child = $term_id; 4256 $ancestors = array(); 4257 while ( ! empty( $terms_by_id[ $child ] ) && $parent = $terms_by_id[ $child ]->parent ) { 4258 $ancestors[] = $child; 4259 4260 if ( ! empty( $term_items[ $term_id ] ) ) { 4261 foreach ( $term_items[ $term_id ] as $item_id => $touches ) { 4262 $term_items[ $parent ][ $item_id ] = isset( $term_items[ $parent ][ $item_id ] ) ? ++$term_items[ $parent ][ $item_id ] : 1; 4263 } 4264 } 4265 4266 $child = $parent; 4267 4268 if ( in_array( $parent, $ancestors, true ) ) { 4269 break; 4270 } 4271 } 4272 } 4273 4274 // Transfer the touched cells. 4275 foreach ( (array) $term_items as $id => $items ) { 4276 if ( isset( $terms_by_id[ $id ] ) ) { 4277 $terms_by_id[ $id ]->count = count( $items ); 4278 } 4279 } 4280 } 4281 4282 /** 4283 * Adds any terms from the given IDs to the cache that do not already exist in cache. 4284 * 4285 * @since 4.6.0 4286 * @since 6.1.0 This function is no longer marked as "private". 4287 * @since 6.3.0 Use wp_lazyload_term_meta() for lazy-loading of term meta. 4288 * 4289 * @global wpdb $wpdb WordPress database abstraction object. 4290 * 4291 * @param array $term_ids Array of term IDs. 4292 * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true. 4293 */ 4294 function _prime_term_caches( $term_ids, $update_meta_cache = true ) { 4295 global $wpdb; 4296 4297 $non_cached_ids = _get_non_cached_ids( $term_ids, 'terms' ); 4298 if ( ! empty( $non_cached_ids ) ) { 4299 $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 ) ) ) ); 4300 4301 update_term_cache( $fresh_terms ); 4302 } 4303 4304 if ( $update_meta_cache ) { 4305 wp_lazyload_term_meta( $term_ids ); 4306 } 4307 } 4308 4309 // 4310 // Default callbacks. 4311 // 4312 4313 /** 4314 * Updates term count based on object types of the current taxonomy. 4315 * 4316 * Private function for the default callback for post_tag and category 4317 * taxonomies. 4318 * 4319 * @access private 4320 * @since 2.3.0 4321 * 4322 * @global wpdb $wpdb WordPress database abstraction object. 4323 * 4324 * @param int[] $terms List of term taxonomy IDs. 4325 * @param WP_Taxonomy $taxonomy Current taxonomy object of terms. 4326 */ 4327 function _update_post_term_count( $terms, $taxonomy ) { 4328 global $wpdb; 4329 4330 $object_types = (array) $taxonomy->object_type; 4331 4332 foreach ( $object_types as &$object_type ) { 4333 list( $object_type ) = explode( ':', $object_type ); 4334 } 4335 4336 $object_types = array_unique( $object_types ); 4337 4338 $check_attachments = array_search( 'attachment', $object_types, true ); 4339 if ( false !== $check_attachments ) { 4340 unset( $object_types[ $check_attachments ] ); 4341 $check_attachments = true; 4342 } 4343 4344 if ( $object_types ) { 4345 $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) ); 4346 } 4347 4348 $post_statuses = array( 'publish' ); 4349 4350 /** 4351 * Filters the post statuses for updating the term count. 4352 * 4353 * @since 5.7.0 4354 * 4355 * @param string[] $post_statuses List of post statuses to include in the count. Default is 'publish'. 4356 * @param WP_Taxonomy $taxonomy Current taxonomy object. 4357 */ 4358 $post_statuses = esc_sql( apply_filters( 'update_post_term_count_statuses', $post_statuses, $taxonomy ) ); 4359 4360 foreach ( (array) $terms as $tt_id ) { 4361 $count = 0; 4362 4363 // Attachments can be 'inherit' status, we need to base count off the parent's status if so. 4364 if ( $check_attachments ) { 4365 // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration 4366 $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 ) ); 4367 } 4368 4369 if ( $object_types ) { 4370 // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.QuotedDynamicPlaceholderGeneration 4371 $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 ) ); 4372 } 4373 4374 /** 4375 * Fires when a term count is calculated, before it is updated in the database. 4376 * 4377 * @since 6.9.0 4378 * 4379 * @param int $tt_id Term taxonomy ID. 4380 * @param string $taxonomy_name Taxonomy slug. 4381 * @param int $count Term count. 4382 */ 4383 do_action( 'update_term_count', $tt_id, $taxonomy->name, $count ); 4384 4385 /** This action is documented in wp-includes/taxonomy.php */ 4386 do_action( 'edit_term_taxonomy', $tt_id, $taxonomy->name, array() ); 4387 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $tt_id ) ); 4388 4389 /** This action is documented in wp-includes/taxonomy.php */ 4390 do_action( 'edited_term_taxonomy', $tt_id, $taxonomy->name, array() ); 4391 } 4392 } 4393 4394 /** 4395 * Updates term count based on number of objects. 4396 * 4397 * Default callback for the 'link_category' taxonomy. 4398 * 4399 * @since 3.3.0 4400 * 4401 * @global wpdb $wpdb WordPress database abstraction object. 4402 * 4403 * @param int[] $terms List of term taxonomy IDs. 4404 * @param WP_Taxonomy $taxonomy Current taxonomy object of terms. 4405 */ 4406 function _update_generic_term_count( $terms, $taxonomy ) { 4407 global $wpdb; 4408 4409 foreach ( (array) $terms as $term ) { 4410 $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) ); 4411 4412 /** This action is documented in wp-includes/taxonomy.php */ 4413 do_action( 'update_term_count', $term, $taxonomy->name, $count ); 4414 4415 /** This action is documented in wp-includes/taxonomy.php */ 4416 do_action( 'edit_term_taxonomy', $term, $taxonomy->name, array() ); 4417 $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) ); 4418 4419 /** This action is documented in wp-includes/taxonomy.php */ 4420 do_action( 'edited_term_taxonomy', $term, $taxonomy->name, array() ); 4421 } 4422 } 4423 4424 /** 4425 * Creates a new term for a term_taxonomy item that currently shares its term 4426 * with another term_taxonomy. 4427 * 4428 * @ignore 4429 * @since 4.2.0 4430 * @since 4.3.0 Introduced `$record` parameter. Also, `$term_id` and 4431 * `$term_taxonomy_id` can now accept objects. 4432 * 4433 * @global wpdb $wpdb WordPress database abstraction object. 4434 * 4435 * @param int|object $term_id ID of the shared term, or the shared term object. 4436 * @param int|object $term_taxonomy_id ID of the term_taxonomy item to receive a new term, or the term_taxonomy object 4437 * (corresponding to a row from the term_taxonomy table). 4438 * @param bool $record Whether to record data about the split term in the options table. The recording 4439 * process has the potential to be resource-intensive, so during batch operations 4440 * it can be beneficial to skip inline recording and do it just once, after the 4441 * batch is processed. Only set this to `false` if you know what you are doing. 4442 * Default: true. 4443 * @return int|WP_Error When the current term does not need to be split (or cannot be split on the current 4444 * database schema), `$term_id` is returned. When the term is successfully split, the 4445 * new term_id is returned. A WP_Error is returned for miscellaneous errors. 4446 */ 4447 function _split_shared_term( $term_id, $term_taxonomy_id, $record = true ) { 4448 global $wpdb; 4449 4450 if ( is_object( $term_id ) ) { 4451 $shared_term = $term_id; 4452 $term_id = (int) $shared_term->term_id; 4453 } 4454 4455 if ( is_object( $term_taxonomy_id ) ) { 4456 $term_taxonomy = $term_taxonomy_id; 4457 $term_taxonomy_id = (int) $term_taxonomy->term_taxonomy_id; 4458 } 4459 4460 // If there are no shared term_taxonomy rows, there's nothing to do here. 4461 $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 ) ); 4462 4463 if ( ! $shared_tt_count ) { 4464 return $term_id; 4465 } 4466 4467 /* 4468 * Verify that the term_taxonomy_id passed to the function is actually associated with the term_id. 4469 * If there's a mismatch, it may mean that the term is already split. Return the actual term_id from the db. 4470 */ 4471 $check_term_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) ); 4472 if ( $check_term_id !== $term_id ) { 4473 return $check_term_id; 4474 } 4475 4476 // Pull up data about the currently shared slug, which we'll use to populate the new one. 4477 if ( empty( $shared_term ) ) { 4478 $shared_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.* FROM $wpdb->terms t WHERE t.term_id = %d", $term_id ) ); 4479 } 4480 4481 $new_term_data = array( 4482 'name' => $shared_term->name, 4483 'slug' => $shared_term->slug, 4484 'term_group' => $shared_term->term_group, 4485 ); 4486 4487 if ( false === $wpdb->insert( $wpdb->terms, $new_term_data ) ) { 4488 return new WP_Error( 'db_insert_error', __( 'Could not split shared term.' ), $wpdb->last_error ); 4489 } 4490 4491 $new_term_id = (int) $wpdb->insert_id; 4492 4493 // Update the existing term_taxonomy to point to the newly created term. 4494 $wpdb->update( 4495 $wpdb->term_taxonomy, 4496 array( 'term_id' => $new_term_id ), 4497 array( 'term_taxonomy_id' => $term_taxonomy_id ) 4498 ); 4499 4500 // Reassign child terms to the new parent. 4501 if ( empty( $term_taxonomy ) ) { 4502 $term_taxonomy = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $term_taxonomy_id ) ); 4503 } 4504 4505 $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 ) ); 4506 if ( ! empty( $children_tt_ids ) ) { 4507 foreach ( $children_tt_ids as $child_tt_id ) { 4508 $wpdb->update( 4509 $wpdb->term_taxonomy, 4510 array( 'parent' => $new_term_id ), 4511 array( 'term_taxonomy_id' => $child_tt_id ) 4512 ); 4513 clean_term_cache( (int) $child_tt_id, '', false ); 4514 } 4515 } else { 4516 // If the term has no children, we must force its taxonomy cache to be rebuilt separately. 4517 clean_term_cache( $new_term_id, $term_taxonomy->taxonomy, false ); 4518 } 4519 4520 clean_term_cache( $term_id, $term_taxonomy->taxonomy, false ); 4521 4522 /* 4523 * Taxonomy cache clearing is delayed to avoid race conditions that may occur when 4524 * regenerating the taxonomy's hierarchy tree. 4525 */ 4526 $taxonomies_to_clean = array( $term_taxonomy->taxonomy ); 4527 4528 // Clean the cache for term taxonomies formerly shared with the current term. 4529 $shared_term_taxonomies = $wpdb->get_col( $wpdb->prepare( "SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) ); 4530 $taxonomies_to_clean = array_merge( $taxonomies_to_clean, $shared_term_taxonomies ); 4531 4532 foreach ( $taxonomies_to_clean as $taxonomy_to_clean ) { 4533 clean_taxonomy_cache( $taxonomy_to_clean ); 4534 } 4535 4536 // Keep a record of term_ids that have been split, keyed by old term_id. See wp_get_split_term(). 4537 if ( $record ) { 4538 $split_term_data = get_option( '_split_terms', array() ); 4539 $split_term_data[ $term_id ] ??= array(); 4540 4541 $split_term_data[ $term_id ][ $term_taxonomy->taxonomy ] = $new_term_id; 4542 update_option( '_split_terms', $split_term_data ); 4543 } 4544 4545 // If we've just split the final shared term, set the "finished" flag. 4546 $shared_terms_exist = $wpdb->get_results( 4547 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt 4548 LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id 4549 GROUP BY t.term_id 4550 HAVING term_tt_count > 1 4551 LIMIT 1" 4552 ); 4553 if ( ! $shared_terms_exist ) { 4554 update_option( 'finished_splitting_shared_terms', true ); 4555 } 4556 4557 /** 4558 * Fires after a previously shared taxonomy term is split into two separate terms. 4559 * 4560 * @since 4.2.0 4561 * 4562 * @param int $term_id ID of the formerly shared term. 4563 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id. 4564 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split. 4565 * @param string $taxonomy Taxonomy for the split term. 4566 */ 4567 do_action( 'split_shared_term', $term_id, $new_term_id, $term_taxonomy_id, $term_taxonomy->taxonomy ); 4568 4569 return $new_term_id; 4570 } 4571 4572 /** 4573 * Splits a batch of shared taxonomy terms. 4574 * 4575 * @since 4.3.0 4576 * 4577 * @global wpdb $wpdb WordPress database abstraction object. 4578 */ 4579 function _wp_batch_split_terms() { 4580 global $wpdb; 4581 4582 $lock_name = 'term_split.lock'; 4583 4584 // Try to lock. 4585 $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'off') /* LOCK */", $lock_name, time() ) ); 4586 4587 if ( ! $lock_result ) { 4588 $lock_result = get_option( $lock_name ); 4589 4590 // Bail if we were unable to create a lock, or if the existing lock is still valid. 4591 if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) { 4592 wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' ); 4593 return; 4594 } 4595 } 4596 4597 // Update the lock, as by this point we've definitely got a lock, just need to fire the actions. 4598 update_option( $lock_name, time() ); 4599 4600 // Get a list of shared terms (those with more than one associated row in term_taxonomy). 4601 $shared_terms = $wpdb->get_results( 4602 "SELECT tt.term_id, t.*, count(*) as term_tt_count FROM {$wpdb->term_taxonomy} tt 4603 LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id 4604 GROUP BY t.term_id 4605 HAVING term_tt_count > 1 4606 LIMIT 10" 4607 ); 4608 4609 // No more terms, we're done here. 4610 if ( ! $shared_terms ) { 4611 update_option( 'finished_splitting_shared_terms', true ); 4612 delete_option( $lock_name ); 4613 return; 4614 } 4615 4616 // Shared terms found? We'll need to run this script again. 4617 wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_split_shared_term_batch' ); 4618 4619 // Rekey shared term array for faster lookups. 4620 $_shared_terms = array(); 4621 foreach ( $shared_terms as $shared_term ) { 4622 $term_id = (int) $shared_term->term_id; 4623 $_shared_terms[ $term_id ] = $shared_term; 4624 } 4625 $shared_terms = $_shared_terms; 4626 4627 // Get term taxonomy data for all shared terms. 4628 $shared_term_ids = implode( ',', array_keys( $shared_terms ) ); 4629 $shared_tts = $wpdb->get_results( "SELECT * FROM {$wpdb->term_taxonomy} WHERE `term_id` IN ({$shared_term_ids})" ); 4630 4631 // Split term data recording is slow, so we do it just once, outside the loop. 4632 $split_term_data = get_option( '_split_terms', array() ); 4633 $skipped_first_term = array(); 4634 $taxonomies = array(); 4635 foreach ( $shared_tts as $shared_tt ) { 4636 $term_id = (int) $shared_tt->term_id; 4637 4638 // Don't split the first tt belonging to a given term_id. 4639 if ( ! isset( $skipped_first_term[ $term_id ] ) ) { 4640 $skipped_first_term[ $term_id ] = 1; 4641 continue; 4642 } 4643 4644 $split_term_data[ $term_id ] ??= array(); 4645 4646 // Keep track of taxonomies whose hierarchies need flushing. 4647 if ( ! isset( $taxonomies[ $shared_tt->taxonomy ] ) ) { 4648 $taxonomies[ $shared_tt->taxonomy ] = 1; 4649 } 4650 4651 // Split the term. 4652 $split_term_data[ $term_id ][ $shared_tt->taxonomy ] = _split_shared_term( $shared_terms[ $term_id ], $shared_tt, false ); 4653 } 4654 4655 // Rebuild the cached hierarchy for each affected taxonomy. 4656 foreach ( array_keys( $taxonomies ) as $tax ) { 4657 delete_option( "{$tax}_children" ); 4658 _get_term_hierarchy( $tax ); 4659 } 4660 4661 update_option( '_split_terms', $split_term_data ); 4662 4663 delete_option( $lock_name ); 4664 } 4665 4666 /** 4667 * In order to avoid the _wp_batch_split_terms() job being accidentally removed, 4668 * checks that it's still scheduled while we haven't finished splitting terms. 4669 * 4670 * @ignore 4671 * @since 4.3.0 4672 */ 4673 function _wp_check_for_scheduled_split_terms() { 4674 if ( ! get_option( 'finished_splitting_shared_terms' ) && ! wp_next_scheduled( 'wp_split_shared_term_batch' ) ) { 4675 wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_split_shared_term_batch' ); 4676 } 4677 } 4678 4679 /** 4680 * Checks default categories when a term gets split to see if any of them need to be updated. 4681 * 4682 * @ignore 4683 * @since 4.2.0 4684 * 4685 * @param int $term_id ID of the formerly shared term. 4686 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id. 4687 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split. 4688 * @param string $taxonomy Taxonomy for the split term. 4689 */ 4690 function _wp_check_split_default_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) { 4691 if ( 'category' !== $taxonomy ) { 4692 return; 4693 } 4694 4695 foreach ( array( 'default_category', 'default_link_category', 'default_email_category' ) as $option ) { 4696 if ( (int) get_option( $option, -1 ) === $term_id ) { 4697 update_option( $option, $new_term_id ); 4698 } 4699 } 4700 } 4701 4702 /** 4703 * Checks menu items when a term gets split to see if any of them need to be updated. 4704 * 4705 * @ignore 4706 * @since 4.2.0 4707 * 4708 * @global wpdb $wpdb WordPress database abstraction object. 4709 * 4710 * @param int $term_id ID of the formerly shared term. 4711 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id. 4712 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split. 4713 * @param string $taxonomy Taxonomy for the split term. 4714 */ 4715 function _wp_check_split_terms_in_menus( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) { 4716 global $wpdb; 4717 $post_ids = $wpdb->get_col( 4718 $wpdb->prepare( 4719 "SELECT m1.post_id 4720 FROM {$wpdb->postmeta} AS m1 4721 INNER JOIN {$wpdb->postmeta} AS m2 ON ( m2.post_id = m1.post_id ) 4722 INNER JOIN {$wpdb->postmeta} AS m3 ON ( m3.post_id = m1.post_id ) 4723 WHERE ( m1.meta_key = '_menu_item_type' AND m1.meta_value = 'taxonomy' ) 4724 AND ( m2.meta_key = '_menu_item_object' AND m2.meta_value = %s ) 4725 AND ( m3.meta_key = '_menu_item_object_id' AND m3.meta_value = %d )", 4726 $taxonomy, 4727 $term_id 4728 ) 4729 ); 4730 4731 if ( $post_ids ) { 4732 foreach ( $post_ids as $post_id ) { 4733 update_post_meta( $post_id, '_menu_item_object_id', $new_term_id, $term_id ); 4734 } 4735 } 4736 } 4737 4738 /** 4739 * If the term being split is a nav_menu, changes associations. 4740 * 4741 * @ignore 4742 * @since 4.3.0 4743 * 4744 * @param int $term_id ID of the formerly shared term. 4745 * @param int $new_term_id ID of the new term created for the $term_taxonomy_id. 4746 * @param int $term_taxonomy_id ID for the term_taxonomy row affected by the split. 4747 * @param string $taxonomy Taxonomy for the split term. 4748 */ 4749 function _wp_check_split_nav_menu_terms( $term_id, $new_term_id, $term_taxonomy_id, $taxonomy ) { 4750 if ( 'nav_menu' !== $taxonomy ) { 4751 return; 4752 } 4753 4754 // Update menu locations. 4755 $locations = get_nav_menu_locations(); 4756 foreach ( $locations as $location => $menu_id ) { 4757 if ( $term_id === $menu_id ) { 4758 $locations[ $location ] = $new_term_id; 4759 } 4760 } 4761 set_theme_mod( 'nav_menu_locations', $locations ); 4762 } 4763 4764 /** 4765 * Gets data about terms that previously shared a single term_id, but have since been split. 4766 * 4767 * @since 4.2.0 4768 * 4769 * @param int $old_term_id Term ID. This is the old, pre-split term ID. 4770 * @return array Array of new term IDs, keyed by taxonomy. 4771 */ 4772 function wp_get_split_terms( $old_term_id ) { 4773 $split_terms = get_option( '_split_terms', array() ); 4774 4775 $terms = array(); 4776 if ( isset( $split_terms[ $old_term_id ] ) ) { 4777 $terms = $split_terms[ $old_term_id ]; 4778 } 4779 4780 return $terms; 4781 } 4782 4783 /** 4784 * Gets the new term ID corresponding to a previously split term. 4785 * 4786 * @since 4.2.0 4787 * 4788 * @param int $old_term_id Term ID. This is the old, pre-split term ID. 4789 * @param string $taxonomy Taxonomy that the term belongs to. 4790 * @return int|false If a previously split term is found corresponding to the old term_id and taxonomy, 4791 * the new term_id will be returned. If no previously split term is found matching 4792 * the parameters, returns false. 4793 */ 4794 function wp_get_split_term( $old_term_id, $taxonomy ) { 4795 $split_terms = wp_get_split_terms( $old_term_id ); 4796 4797 $term_id = false; 4798 if ( isset( $split_terms[ $taxonomy ] ) ) { 4799 $term_id = (int) $split_terms[ $taxonomy ]; 4800 } 4801 4802 return $term_id; 4803 } 4804 4805 /** 4806 * Determines whether a term is shared between multiple taxonomies. 4807 * 4808 * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or 4809 * other delays in upgrade routines may cause shared terms to remain. 4810 * 4811 * @since 4.4.0 4812 * 4813 * @global wpdb $wpdb WordPress database abstraction object. 4814 * 4815 * @param int $term_id Term ID. 4816 * @return bool Returns false if a term is not shared between multiple taxonomies or 4817 * if splitting shared taxonomy terms is finished. 4818 */ 4819 function wp_term_is_shared( $term_id ) { 4820 global $wpdb; 4821 4822 if ( get_option( 'finished_splitting_shared_terms' ) ) { 4823 return false; 4824 } 4825 4826 $tt_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term_id ) ); 4827 4828 return $tt_count > 1; 4829 } 4830 4831 /** 4832 * Generates a permalink for a taxonomy term archive. 4833 * 4834 * @since 2.5.0 4835 * 4836 * @global WP_Rewrite $wp_rewrite WordPress rewrite component. 4837 * 4838 * @param WP_Term|int|string $term The term object, ID, or slug whose link will be retrieved. 4839 * @param string $taxonomy Optional. Taxonomy. Default empty. 4840 * @return string|WP_Error URL of the taxonomy term archive on success, WP_Error if term does not exist. 4841 */ 4842 function get_term_link( $term, $taxonomy = '' ) { 4843 global $wp_rewrite; 4844 4845 if ( ! is_object( $term ) ) { 4846 if ( is_int( $term ) ) { 4847 $term = get_term( $term, $taxonomy ); 4848 } else { 4849 $term = get_term_by( 'slug', $term, $taxonomy ); 4850 } 4851 } 4852 4853 if ( ! is_object( $term ) ) { 4854 $term = new WP_Error( 'invalid_term', __( 'Empty Term.' ) ); 4855 } 4856 4857 if ( is_wp_error( $term ) ) { 4858 return $term; 4859 } 4860 4861 $taxonomy = $term->taxonomy; 4862 4863 $termlink = $wp_rewrite->get_extra_permastruct( $taxonomy ); 4864 4865 /** 4866 * Filters the permalink structure for a term before token replacement occurs. 4867 * 4868 * @since 4.9.0 4869 * 4870 * @param string $termlink The permalink structure for the term's taxonomy. 4871 * @param WP_Term $term The term object. 4872 */ 4873 $termlink = apply_filters( 'pre_term_link', $termlink, $term ); 4874 4875 $slug = $term->slug; 4876 $t = get_taxonomy( $taxonomy ); 4877 4878 if ( empty( $termlink ) ) { 4879 if ( 'category' === $taxonomy ) { 4880 $termlink = '?cat=' . $term->term_id; 4881 } elseif ( $t->query_var ) { 4882 $termlink = "?$t->query_var=$slug"; 4883 } else { 4884 $termlink = "?taxonomy=$taxonomy&term=$slug"; 4885 } 4886 $termlink = home_url( $termlink ); 4887 } else { 4888 if ( ! empty( $t->rewrite['hierarchical'] ) ) { 4889 $hierarchical_slugs = array(); 4890 $ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' ); 4891 foreach ( (array) $ancestors as $ancestor ) { 4892 $ancestor_term = get_term( $ancestor, $taxonomy ); 4893 $hierarchical_slugs[] = $ancestor_term->slug; 4894 } 4895 $hierarchical_slugs = array_reverse( $hierarchical_slugs ); 4896 $hierarchical_slugs[] = $slug; 4897 $termlink = str_replace( "%$taxonomy%", implode( '/', $hierarchical_slugs ), $termlink ); 4898 } else { 4899 $termlink = str_replace( "%$taxonomy%", $slug, $termlink ); 4900 } 4901 $termlink = home_url( user_trailingslashit( $termlink, 'category' ) ); 4902 } 4903 4904 // Back compat filters. 4905 if ( 'post_tag' === $taxonomy ) { 4906 4907 /** 4908 * Filters the tag link. 4909 * 4910 * @since 2.3.0 4911 * @since 2.5.0 Deprecated in favor of {@see 'term_link'} filter. 4912 * @since 5.4.1 Restored (un-deprecated). 4913 * 4914 * @param string $termlink Tag link URL. 4915 * @param int $term_id Term ID. 4916 */ 4917 $termlink = apply_filters( 'tag_link', $termlink, $term->term_id ); 4918 } elseif ( 'category' === $taxonomy ) { 4919 4920 /** 4921 * Filters the category link. 4922 * 4923 * @since 1.5.0 4924 * @since 2.5.0 Deprecated in favor of {@see 'term_link'} filter. 4925 * @since 5.4.1 Restored (un-deprecated). 4926 * 4927 * @param string $termlink Category link URL. 4928 * @param int $term_id Term ID. 4929 */ 4930 $termlink = apply_filters( 'category_link', $termlink, $term->term_id ); 4931 } 4932 4933 /** 4934 * Filters the term link. 4935 * 4936 * @since 2.5.0 4937 * 4938 * @param string $termlink Term link URL. 4939 * @param WP_Term $term Term object. 4940 * @param string $taxonomy Taxonomy slug. 4941 */ 4942 return apply_filters( 'term_link', $termlink, $term, $taxonomy ); 4943 } 4944 4945 /** 4946 * Displays the taxonomies of a post with available options. 4947 * 4948 * This function can be used within the loop to display the taxonomies for a 4949 * post without specifying the Post ID. You can also use it outside the Loop to 4950 * display the taxonomies for a specific post. 4951 * 4952 * @since 2.5.0 4953 * 4954 * @param array $args { 4955 * Arguments about which post to use and how to format the output. Shares all of the arguments 4956 * supported by get_the_taxonomies(), in addition to the following. 4957 * 4958 * @type int|WP_Post $post Post ID or object to get taxonomies of. Default current post. 4959 * @type string $before Displays before the taxonomies. Default empty string. 4960 * @type string $sep Separates each taxonomy. Default is a space. 4961 * @type string $after Displays after the taxonomies. Default empty string. 4962 * } 4963 */ 4964 function the_taxonomies( $args = array() ) { 4965 $defaults = array( 4966 'post' => 0, 4967 'before' => '', 4968 'sep' => ' ', 4969 'after' => '', 4970 ); 4971 4972 $parsed_args = wp_parse_args( $args, $defaults ); 4973 4974 echo $parsed_args['before'] . implode( $parsed_args['sep'], get_the_taxonomies( $parsed_args['post'], $parsed_args ) ) . $parsed_args['after']; 4975 } 4976 4977 /** 4978 * Retrieves all taxonomies associated with a post. 4979 * 4980 * This function can be used within the loop. It will also return an array of 4981 * the taxonomies with links to the taxonomy and name. 4982 * 4983 * @since 2.5.0 4984 * 4985 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. 4986 * @param array $args { 4987 * Optional. Arguments about how to format the list of taxonomies. Default empty array. 4988 * 4989 * @type string $template Template for displaying a taxonomy label and list of terms. 4990 * Default is "Label: Terms." 4991 * @type string $term_template Template for displaying a single term in the list. Default is the term name 4992 * linked to its archive. 4993 * } 4994 * @return string[] List of taxonomies. 4995 */ 4996 function get_the_taxonomies( $post = 0, $args = array() ) { 4997 $post = get_post( $post ); 4998 4999 $args = wp_parse_args( 5000 $args, 5001 array( 5002 /* translators: %s: Taxonomy label, %l: List of terms formatted as per $term_template. */ 5003 'template' => __( '%s: %l.' ), 5004 'term_template' => '<a href="%1$s">%2$s</a>', 5005 ) 5006 ); 5007 5008 $taxonomies = array(); 5009 5010 if ( ! $post ) { 5011 return $taxonomies; 5012 } 5013 5014 foreach ( get_object_taxonomies( $post ) as $taxonomy ) { 5015 $t = (array) get_taxonomy( $taxonomy ); 5016 if ( empty( $t['label'] ) ) { 5017 $t['label'] = $taxonomy; 5018 } 5019 if ( empty( $t['args'] ) ) { 5020 $t['args'] = array(); 5021 } 5022 if ( empty( $t['template'] ) ) { 5023 $t['template'] = $args['template']; 5024 } 5025 if ( empty( $t['term_template'] ) ) { 5026 $t['term_template'] = $args['term_template']; 5027 } 5028 5029 $terms = get_object_term_cache( $post->ID, $taxonomy ); 5030 if ( false === $terms ) { 5031 $terms = wp_get_object_terms( $post->ID, $taxonomy, $t['args'] ); 5032 } 5033 $links = array(); 5034 5035 foreach ( $terms as $term ) { 5036 $links[] = wp_sprintf( $t['term_template'], esc_attr( get_term_link( $term ) ), $term->name ); 5037 } 5038 if ( $links ) { 5039 $taxonomies[ $taxonomy ] = wp_sprintf( $t['template'], $t['label'], $links, $terms ); 5040 } 5041 } 5042 return $taxonomies; 5043 } 5044 5045 /** 5046 * Retrieves all taxonomy names for the given post. 5047 * 5048 * @since 2.5.0 5049 * 5050 * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post. 5051 * @return string[] An array of all taxonomy names for the given post. 5052 */ 5053 function get_post_taxonomies( $post = 0 ) { 5054 $post = get_post( $post ); 5055 5056 return get_object_taxonomies( $post ); 5057 } 5058 5059 /** 5060 * Determines if the given object is associated with any of the given terms. 5061 * 5062 * The given terms are checked against the object's terms' term_ids, names and slugs. 5063 * Terms given as integers will only be checked against the object's terms' term_ids. 5064 * If no terms are given, determines if object is associated with any terms in the given taxonomy. 5065 * 5066 * @since 2.7.0 5067 * 5068 * @param int $object_id ID of the object (post ID, link ID, ...). 5069 * @param string $taxonomy Single taxonomy name. 5070 * @param int|string|int[]|string[] $terms Optional. Term ID, name, slug, or array of such 5071 * to check against. Default null. 5072 * @return bool|WP_Error WP_Error on input error. 5073 */ 5074 function is_object_in_term( $object_id, $taxonomy, $terms = null ) { 5075 $object_id = (int) $object_id; 5076 if ( ! $object_id ) { 5077 return new WP_Error( 'invalid_object', __( 'Invalid object ID.' ) ); 5078 } 5079 5080 $object_terms = get_object_term_cache( $object_id, $taxonomy ); 5081 if ( false === $object_terms ) { 5082 $object_terms = wp_get_object_terms( $object_id, $taxonomy, array( 'update_term_meta_cache' => false ) ); 5083 if ( is_wp_error( $object_terms ) ) { 5084 return $object_terms; 5085 } 5086 5087 wp_cache_set( $object_id, wp_list_pluck( $object_terms, 'term_id' ), "{$taxonomy}_relationships" ); 5088 } 5089 5090 if ( is_wp_error( $object_terms ) ) { 5091 return $object_terms; 5092 } 5093 5094 if ( empty( $object_terms ) ) { 5095 return false; 5096 } 5097 5098 if ( empty( $terms ) ) { 5099 return true; 5100 } 5101 5102 $terms = (array) $terms; 5103 5104 $ints = array_filter( $terms, 'is_int' ); 5105 if ( $ints ) { 5106 $strs = array_diff( $terms, $ints ); 5107 } else { 5108 $strs =& $terms; 5109 } 5110 5111 foreach ( $object_terms as $object_term ) { 5112 // If term is an int, check against term_ids only. 5113 if ( $ints && in_array( $object_term->term_id, $ints, true ) ) { 5114 return true; 5115 } 5116 5117 if ( $strs ) { 5118 // Only check numeric strings against term_id, to avoid false matches due to type juggling. 5119 $numeric_strs = array_map( 'intval', array_filter( $strs, 'is_numeric' ) ); 5120 if ( in_array( $object_term->term_id, $numeric_strs, true ) ) { 5121 return true; 5122 } 5123 5124 if ( in_array( $object_term->name, $strs, true ) ) { 5125 return true; 5126 } 5127 if ( in_array( $object_term->slug, $strs, true ) ) { 5128 return true; 5129 } 5130 } 5131 } 5132 5133 return false; 5134 } 5135 5136 /** 5137 * Determines if the given object type is associated with the given taxonomy. 5138 * 5139 * @since 3.0.0 5140 * 5141 * @param string $object_type Object type string. 5142 * @param string $taxonomy Single taxonomy name. 5143 * @return bool True if object is associated with the taxonomy, otherwise false. 5144 */ 5145 function is_object_in_taxonomy( $object_type, $taxonomy ) { 5146 $taxonomies = get_object_taxonomies( $object_type ); 5147 if ( empty( $taxonomies ) ) { 5148 return false; 5149 } 5150 return in_array( $taxonomy, $taxonomies, true ); 5151 } 5152 5153 /** 5154 * Gets an array of ancestor IDs for a given object. 5155 * 5156 * @since 3.1.0 5157 * @since 4.1.0 Introduced the `$resource_type` argument. 5158 * 5159 * @param int $object_id Optional. The ID of the object. Default 0. 5160 * @param string $object_type Optional. The type of object for which we'll be retrieving 5161 * ancestors. Accepts a post type or a taxonomy name. Default empty. 5162 * @param string $resource_type Optional. Type of resource $object_type is. Accepts 'post_type' 5163 * or 'taxonomy'. Default empty. 5164 * @return int[] An array of IDs of ancestors from lowest to highest in the hierarchy. 5165 */ 5166 function get_ancestors( $object_id = 0, $object_type = '', $resource_type = '' ) { 5167 $object_id = (int) $object_id; 5168 5169 $ancestors = array(); 5170 5171 if ( empty( $object_id ) ) { 5172 5173 /** This filter is documented in wp-includes/taxonomy.php */ 5174 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type ); 5175 } 5176 5177 if ( ! $resource_type ) { 5178 if ( is_taxonomy_hierarchical( $object_type ) ) { 5179 $resource_type = 'taxonomy'; 5180 } elseif ( post_type_exists( $object_type ) ) { 5181 $resource_type = 'post_type'; 5182 } 5183 } 5184 5185 if ( 'taxonomy' === $resource_type ) { 5186 $term = get_term( $object_id, $object_type ); 5187 while ( ! is_wp_error( $term ) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors, true ) ) { 5188 $ancestors[] = (int) $term->parent; 5189 $term = get_term( $term->parent, $object_type ); 5190 } 5191 } elseif ( 'post_type' === $resource_type ) { 5192 $ancestors = get_post_ancestors( $object_id ); 5193 } 5194 5195 /** 5196 * Filters a given object's ancestors. 5197 * 5198 * @since 3.1.0 5199 * @since 4.1.1 Introduced the `$resource_type` parameter. 5200 * 5201 * @param int[] $ancestors An array of IDs of object ancestors. 5202 * @param int $object_id Object ID. 5203 * @param string $object_type Type of object. 5204 * @param string $resource_type Type of resource $object_type is. 5205 */ 5206 return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type, $resource_type ); 5207 } 5208 5209 /** 5210 * Returns the term's parent's term ID. 5211 * 5212 * @since 3.1.0 5213 * 5214 * @param int $term_id Term ID. 5215 * @param string $taxonomy Taxonomy name. 5216 * @return int|false Parent term ID on success, false on failure. 5217 */ 5218 function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) { 5219 $term = get_term( $term_id, $taxonomy ); 5220 if ( ! $term || is_wp_error( $term ) ) { 5221 return false; 5222 } 5223 return (int) $term->parent; 5224 } 5225 5226 /** 5227 * Checks the given subset of the term hierarchy for hierarchy loops. 5228 * Prevents loops from forming and breaks those that it finds. 5229 * 5230 * Attached to the {@see 'wp_update_term_parent'} filter. 5231 * 5232 * @since 3.1.0 5233 * 5234 * @param int $parent_term `term_id` of the parent for the term we're checking. 5235 * @param int $term_id The term we're checking. 5236 * @param string $taxonomy The taxonomy of the term we're checking. 5237 * @return int The new parent for the term. 5238 */ 5239 function wp_check_term_hierarchy_for_loops( $parent_term, $term_id, $taxonomy ) { 5240 // Nothing fancy here - bail. 5241 if ( ! $parent_term ) { 5242 return 0; 5243 } 5244 5245 // Can't be its own parent. 5246 if ( $parent_term === $term_id ) { 5247 return 0; 5248 } 5249 5250 // Now look for larger loops. 5251 $loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent_term, array( $taxonomy ) ); 5252 if ( ! $loop ) { 5253 return $parent_term; // No loop. 5254 } 5255 5256 // Setting $parent_term to the given value causes a loop. 5257 if ( isset( $loop[ $term_id ] ) ) { 5258 return 0; 5259 } 5260 5261 // There's a loop, but it doesn't contain $term_id. Break the loop. 5262 foreach ( array_keys( $loop ) as $loop_member ) { 5263 wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) ); 5264 } 5265 5266 return $parent_term; 5267 } 5268 5269 /** 5270 * Determines whether a taxonomy is considered "viewable". 5271 * 5272 * @since 5.1.0 5273 * 5274 * @param string|WP_Taxonomy $taxonomy Taxonomy name or object. 5275 * @return bool Whether the taxonomy should be considered viewable. 5276 */ 5277 function is_taxonomy_viewable( $taxonomy ) { 5278 if ( is_scalar( $taxonomy ) ) { 5279 $taxonomy = get_taxonomy( $taxonomy ); 5280 if ( ! $taxonomy ) { 5281 return false; 5282 } 5283 } 5284 5285 return $taxonomy->publicly_queryable; 5286 } 5287 5288 /** 5289 * Determines whether a term is publicly viewable. 5290 * 5291 * A term is considered publicly viewable if its taxonomy is viewable. 5292 * 5293 * @since 6.1.0 5294 * 5295 * @param int|WP_Term $term Term ID or term object. 5296 * @return bool Whether the term is publicly viewable. 5297 */ 5298 function is_term_publicly_viewable( $term ) { 5299 $term = get_term( $term ); 5300 5301 if ( ! $term ) { 5302 return false; 5303 } 5304 5305 return is_taxonomy_viewable( $term->taxonomy ); 5306 } 5307 5308 /** 5309 * Sets the last changed time for the 'terms' cache group. 5310 * 5311 * @since 5.0.0 5312 */ 5313 function wp_cache_set_terms_last_changed() { 5314 wp_cache_set_last_changed( 'terms' ); 5315 } 5316 5317 /** 5318 * Aborts calls to term meta if it is not supported. 5319 * 5320 * @since 5.0.0 5321 * 5322 * @param mixed $check Skip-value for whether to proceed term meta function execution. 5323 * @return mixed Original value of $check, or false if term meta is not supported. 5324 */ 5325 function wp_check_term_meta_support_prefilter( $check ) { 5326 if ( get_option( 'db_version' ) < 34370 ) { 5327 return false; 5328 } 5329 5330 return $check; 5331 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Fri Dec 4 08:20:01 2026 | Cross-referenced by PHPXref |