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