[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 3 /** 4 * Taxonomy API: WP_Term_Query class. 5 * 6 * @package WordPress 7 * @subpackage Taxonomy 8 * @since 4.6.0 9 */ 10 11 /** 12 * Class used for querying terms. 13 * 14 * @since 4.6.0 15 * 16 * @see WP_Term_Query::__construct() for accepted arguments. 17 */ 18 #[AllowDynamicProperties] 19 class WP_Term_Query { 20 21 /** 22 * SQL string used to perform database query. 23 * 24 * @since 4.6.0 25 * @var string 26 */ 27 public $request; 28 29 /** 30 * Metadata query container. 31 * 32 * @since 4.6.0 33 * @var WP_Meta_Query A meta query instance. 34 */ 35 public $meta_query = false; 36 37 /** 38 * Metadata query clauses. 39 * 40 * @since 4.6.0 41 * @var array 42 */ 43 protected $meta_query_clauses; 44 45 /** 46 * SQL query clauses. 47 * 48 * @since 4.6.0 49 * @var array 50 */ 51 protected $sql_clauses = array( 52 'select' => '', 53 'from' => '', 54 'where' => array(), 55 'orderby' => '', 56 'limits' => '', 57 ); 58 59 /** 60 * Query vars set by the user. 61 * 62 * @since 4.6.0 63 * @var array 64 */ 65 public $query_vars; 66 67 /** 68 * Default values for query vars. 69 * 70 * @since 4.6.0 71 * @var array 72 */ 73 public $query_var_defaults; 74 75 /** 76 * List of terms located by the query. 77 * 78 * @since 4.6.0 79 * @var array 80 */ 81 public $terms; 82 83 /** 84 * Constructor. 85 * 86 * Sets up the term query, based on the query vars passed. 87 * 88 * @since 4.6.0 89 * @since 4.6.0 Introduced 'term_taxonomy_id' parameter. 90 * @since 4.7.0 Introduced 'object_ids' parameter. 91 * @since 4.9.0 Added 'slug__in' support for 'orderby'. 92 * @since 5.1.0 Introduced the 'meta_compare_key' parameter. 93 * @since 5.3.0 Introduced the 'meta_type_key' parameter. 94 * @since 6.4.0 Introduced the 'cache_results' parameter. 95 * 96 * @param string|array $query { 97 * Optional. Array or query string of term query parameters. Default empty. 98 * 99 * @type string|string[] $taxonomy Taxonomy name, or array of taxonomy names, to which results 100 * should be limited. 101 * @type int|int[] $object_ids Object ID, or array of object IDs. Results will be 102 * limited to terms associated with these objects. 103 * @type string $orderby Field(s) to order terms by. Accepts: 104 * - Term fields ('name', 'slug', 'term_group', 'term_id', 'id', 105 * 'description', 'parent', 'term_order'). Unless `$object_ids` 106 * is not empty, 'term_order' is treated the same as 'term_id'. 107 * - 'count' to use the number of objects associated with the term. 108 * - 'include' to match the 'order' of the `$include` param. 109 * - 'slug__in' to match the 'order' of the `$slug` param. 110 * - 'meta_value' 111 * - 'meta_value_num'. 112 * - The value of `$meta_key`. 113 * - The array keys of `$meta_query`. 114 * - 'none' to omit the ORDER BY clause. 115 * Default 'name'. 116 * @type string $order Whether to order terms in ascending or descending order. 117 * Accepts 'ASC' (ascending) or 'DESC' (descending). 118 * Default 'ASC'. 119 * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts 120 * 1|true or 0|false. Default 1|true. 121 * @type int[]|string $include Array or comma/space-separated string of term IDs to include. 122 * Default empty array. 123 * @type int[]|string $exclude Array or comma/space-separated string of term IDs to exclude. 124 * If `$include` is non-empty, `$exclude` is ignored. 125 * Default empty array. 126 * @type int[]|string $exclude_tree Array or comma/space-separated string of term IDs to exclude 127 * along with all of their descendant terms. If `$include` is 128 * non-empty, `$exclude_tree` is ignored. Default empty array. 129 * @type int|string $number Maximum number of terms to return. Accepts ''|0 (all) or any 130 * positive number. Default ''|0 (all). Note that `$number` may 131 * not return accurate results when coupled with `$object_ids`. 132 * See #41796 for details. 133 * @type int $offset The number by which to offset the terms query. Default empty. 134 * @type string $fields Term fields to query for. Accepts: 135 * - 'all' Returns an array of complete term objects (`WP_Term[]`). 136 * - 'all_with_object_id' Returns an array of term objects 137 * with the 'object_id' param (`WP_Term[]`). Works only 138 * when the `$object_ids` parameter is populated. 139 * - 'ids' Returns an array of term IDs (`int[]`). 140 * - 'tt_ids' Returns an array of term taxonomy IDs (`int[]`). 141 * - 'names' Returns an array of term names (`string[]`). 142 * - 'slugs' Returns an array of term slugs (`string[]`). 143 * - 'count' Returns the number of matching terms (`int`). 144 * - 'id=>parent' Returns an associative array of parent term IDs, 145 * keyed by term ID (`int[]`). 146 * - 'id=>name' Returns an associative array of term names, 147 * keyed by term ID (`string[]`). 148 * - 'id=>slug' Returns an associative array of term slugs, 149 * keyed by term ID (`string[]`). 150 * Default 'all'. 151 * @type bool $count Whether to return a term count. If true, will take precedence 152 * over `$fields`. Default false. 153 * @type string|string[] $name Name or array of names to return term(s) for. 154 * Default empty. 155 * @type string|string[] $slug Slug or array of slugs to return term(s) for. 156 * Default empty. 157 * @type int|int[] $term_taxonomy_id Term taxonomy ID, or array of term taxonomy IDs, 158 * to match when querying terms. 159 * @type bool $hierarchical Whether to include terms that have non-empty descendants 160 * (even if `$hide_empty` is set to true). Default true. 161 * @type string $search Search criteria to match terms. Will be SQL-formatted with 162 * wildcards before and after. Default empty. 163 * @type string $name__like Retrieve terms with criteria by which a term is LIKE 164 * `$name__like`. Default empty. 165 * @type string $description__like Retrieve terms where the description is LIKE 166 * `$description__like`. Default empty. 167 * @type bool $pad_counts Whether to pad the quantity of a term's children in the 168 * quantity of each term's "count" object variable. 169 * Default false. 170 * @type string $get Whether to return terms regardless of ancestry or whether the 171 * terms are empty. Accepts 'all' or '' (disabled). 172 * Default ''. 173 * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies 174 * are passed, `$child_of` is ignored. Default 0. 175 * @type int $parent Parent term ID to retrieve direct-child terms of. 176 * Default empty. 177 * @type bool $childless True to limit results to terms that have no children. 178 * This parameter has no effect on non-hierarchical taxonomies. 179 * Default false. 180 * @type string $cache_domain Unique cache key to be produced when this query is stored in 181 * an object cache. Default 'core'. 182 * @type bool $cache_results Whether to cache term information. Default true. 183 * @type bool $update_term_meta_cache Whether to prime meta caches for matched terms. Default true. 184 * @type string|string[] $meta_key Meta key or keys to filter by. 185 * @type string|string[] $meta_value Meta value or values to filter by. 186 * @type string $meta_compare MySQL operator used for comparing the meta value. 187 * See WP_Meta_Query::__construct() for accepted values and default value. 188 * @type string $meta_compare_key MySQL operator used for comparing the meta key. 189 * See WP_Meta_Query::__construct() for accepted values and default value. 190 * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. 191 * See WP_Meta_Query::__construct() for accepted values and default value. 192 * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. 193 * See WP_Meta_Query::__construct() for accepted values and default value. 194 * @type array $meta_query An associative array of WP_Meta_Query arguments. 195 * See WP_Meta_Query::__construct() for accepted values. 196 * } 197 */ 198 public function __construct( $query = '' ) { 199 $this->query_var_defaults = array( 200 'taxonomy' => null, 201 'object_ids' => null, 202 'orderby' => 'name', 203 'order' => 'ASC', 204 'hide_empty' => true, 205 'include' => array(), 206 'exclude' => array(), 207 'exclude_tree' => array(), 208 'number' => '', 209 'offset' => '', 210 'fields' => 'all', 211 'count' => false, 212 'name' => '', 213 'slug' => '', 214 'term_taxonomy_id' => '', 215 'hierarchical' => true, 216 'search' => '', 217 'name__like' => '', 218 'description__like' => '', 219 'pad_counts' => false, 220 'get' => '', 221 'child_of' => 0, 222 'parent' => '', 223 'childless' => false, 224 'cache_domain' => 'core', 225 'cache_results' => true, 226 'update_term_meta_cache' => true, 227 'meta_query' => '', 228 'meta_key' => '', 229 'meta_value' => '', 230 'meta_type' => '', 231 'meta_compare' => '', 232 ); 233 234 if ( ! empty( $query ) ) { 235 $this->query( $query ); 236 } 237 } 238 239 /** 240 * Parse arguments passed to the term query with default query parameters. 241 * 242 * @since 4.6.0 243 * 244 * @param string|array $query WP_Term_Query arguments. See WP_Term_Query::__construct() for accepted arguments. 245 */ 246 public function parse_query( $query = '' ) { 247 if ( empty( $query ) ) { 248 $query = $this->query_vars; 249 } 250 251 $taxonomies = isset( $query['taxonomy'] ) ? (array) $query['taxonomy'] : null; 252 253 /** 254 * Filters the terms query default arguments. 255 * 256 * Use {@see 'get_terms_args'} to filter the passed arguments. 257 * 258 * @since 4.4.0 259 * 260 * @param array $defaults An array of default get_terms() arguments. 261 * @param string[] $taxonomies An array of taxonomy names. 262 */ 263 $this->query_var_defaults = apply_filters( 'get_terms_defaults', $this->query_var_defaults, $taxonomies ); 264 265 $query = wp_parse_args( $query, $this->query_var_defaults ); 266 267 $query['number'] = absint( $query['number'] ); 268 $query['offset'] = absint( $query['offset'] ); 269 270 // 'parent' overrides 'child_of'. 271 if ( 0 < (int) $query['parent'] ) { 272 $query['child_of'] = false; 273 } 274 275 if ( 'all' === $query['get'] ) { 276 $query['childless'] = false; 277 $query['child_of'] = 0; 278 $query['hide_empty'] = 0; 279 $query['hierarchical'] = false; 280 $query['pad_counts'] = false; 281 } 282 283 $query['taxonomy'] = $taxonomies; 284 285 $this->query_vars = $query; 286 287 /** 288 * Fires after term query vars have been parsed. 289 * 290 * @since 4.6.0 291 * 292 * @param WP_Term_Query $query Current instance of WP_Term_Query. 293 */ 294 do_action( 'parse_term_query', $this ); 295 } 296 297 /** 298 * Sets up the query and retrieves the results. 299 * 300 * The return type varies depending on the value passed to `$args['fields']`. See 301 * WP_Term_Query::get_terms() for details. 302 * 303 * @since 4.6.0 304 * 305 * @param string|array $query Array or URL query string of parameters. 306 * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string 307 * when 'count' is passed as a query var. 308 */ 309 public function query( $query ) { 310 $this->query_vars = wp_parse_args( $query ); 311 return $this->get_terms(); 312 } 313 314 /** 315 * Retrieves the query results. 316 * 317 * The return type varies depending on the value passed to `$args['fields']`. 318 * 319 * The following will result in an array of `WP_Term` objects being returned: 320 * 321 * - 'all' 322 * - 'all_with_object_id' 323 * 324 * The following will result in a numeric string being returned: 325 * 326 * - 'count' 327 * 328 * The following will result in an array of text strings being returned: 329 * 330 * - 'id=>name' 331 * - 'id=>slug' 332 * - 'names' 333 * - 'slugs' 334 * 335 * The following will result in an array of numeric strings being returned: 336 * 337 * - 'id=>parent' 338 * 339 * The following will result in an array of integers being returned: 340 * 341 * - 'ids' 342 * - 'tt_ids' 343 * 344 * @since 4.6.0 345 * 346 * @global wpdb $wpdb WordPress database abstraction object. 347 * 348 * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string 349 * when 'count' is passed as a query var. 350 */ 351 public function get_terms() { 352 global $wpdb; 353 354 $this->parse_query( $this->query_vars ); 355 $args = &$this->query_vars; 356 357 // Set up meta_query so it's available to 'pre_get_terms'. 358 $this->meta_query = new WP_Meta_Query(); 359 $this->meta_query->parse_query_vars( $args ); 360 361 /** 362 * Fires before terms are retrieved. 363 * 364 * @since 4.6.0 365 * 366 * @param WP_Term_Query $query Current instance of WP_Term_Query (passed by reference). 367 */ 368 do_action_ref_array( 'pre_get_terms', array( &$this ) ); 369 370 $taxonomies = (array) $args['taxonomy']; 371 372 // Save queries by not crawling the tree in the case of multiple taxes or a flat tax. 373 $has_hierarchical_tax = false; 374 if ( $taxonomies ) { 375 foreach ( $taxonomies as $_tax ) { 376 if ( is_taxonomy_hierarchical( $_tax ) ) { 377 $has_hierarchical_tax = true; 378 } 379 } 380 } else { 381 // When no taxonomies are provided, assume we have to descend the tree. 382 $has_hierarchical_tax = true; 383 } 384 385 if ( ! $has_hierarchical_tax ) { 386 $args['hierarchical'] = false; 387 $args['pad_counts'] = false; 388 } 389 390 // 'parent' overrides 'child_of'. 391 if ( 0 < (int) $args['parent'] ) { 392 $args['child_of'] = false; 393 } 394 395 if ( 'all' === $args['get'] ) { 396 $args['childless'] = false; 397 $args['child_of'] = 0; 398 $args['hide_empty'] = 0; 399 $args['hierarchical'] = false; 400 $args['pad_counts'] = false; 401 } 402 403 /** 404 * Filters the terms query arguments. 405 * 406 * @since 3.1.0 407 * 408 * @param array $args An array of get_terms() arguments. 409 * @param string[] $taxonomies An array of taxonomy names. 410 */ 411 $args = apply_filters( 'get_terms_args', $args, $taxonomies ); 412 413 // Avoid the query if the queried parent/child_of term has no descendants. 414 $child_of = $args['child_of']; 415 $parent = $args['parent']; 416 417 if ( $child_of ) { 418 $_parent = $child_of; 419 } elseif ( $parent ) { 420 $_parent = $parent; 421 } else { 422 $_parent = false; 423 } 424 425 if ( $_parent ) { 426 $in_hierarchy = false; 427 foreach ( $taxonomies as $_tax ) { 428 $hierarchy = _get_term_hierarchy( $_tax ); 429 430 if ( isset( $hierarchy[ $_parent ] ) ) { 431 $in_hierarchy = true; 432 } 433 } 434 435 if ( ! $in_hierarchy ) { 436 if ( 'count' === $args['fields'] ) { 437 return 0; 438 } else { 439 $this->terms = array(); 440 return $this->terms; 441 } 442 } 443 } 444 445 // 'term_order' is a legal sort order only when joining the relationship table. 446 $_orderby = $this->query_vars['orderby']; 447 if ( 'term_order' === $_orderby && empty( $this->query_vars['object_ids'] ) ) { 448 $_orderby = 'term_id'; 449 } 450 451 $orderby = $this->parse_orderby( $_orderby ); 452 453 if ( $orderby ) { 454 $orderby = "ORDER BY $orderby"; 455 } 456 457 $order = $this->parse_order( $this->query_vars['order'] ); 458 459 if ( $taxonomies ) { 460 $this->sql_clauses['where']['taxonomy'] = 461 "tt.taxonomy IN ('" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "')"; 462 } 463 464 if ( empty( $args['exclude'] ) ) { 465 $args['exclude'] = array(); 466 } 467 468 if ( empty( $args['include'] ) ) { 469 $args['include'] = array(); 470 } 471 472 $exclude = $args['exclude']; 473 $exclude_tree = $args['exclude_tree']; 474 $include = $args['include']; 475 476 $inclusions = ''; 477 if ( ! empty( $include ) ) { 478 $exclude = ''; 479 $exclude_tree = ''; 480 $inclusions = implode( ',', wp_parse_id_list( $include ) ); 481 } 482 483 if ( ! empty( $inclusions ) ) { 484 $this->sql_clauses['where']['inclusions'] = 't.term_id IN ( ' . $inclusions . ' )'; 485 } 486 487 $exclusions = array(); 488 if ( ! empty( $exclude_tree ) ) { 489 $exclude_tree = wp_parse_id_list( $exclude_tree ); 490 $excluded_children = $exclude_tree; 491 492 foreach ( $exclude_tree as $extrunk ) { 493 $excluded_children = array_merge( 494 $excluded_children, 495 (array) get_terms( 496 array( 497 'taxonomy' => reset( $taxonomies ), 498 'child_of' => (int) $extrunk, 499 'fields' => 'ids', 500 'hide_empty' => 0, 501 ) 502 ) 503 ); 504 } 505 506 $exclusions = array_merge( $excluded_children, $exclusions ); 507 } 508 509 if ( ! empty( $exclude ) ) { 510 $exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions ); 511 } 512 513 // 'childless' terms are those without an entry in the flattened term hierarchy. 514 $childless = (bool) $args['childless']; 515 if ( $childless ) { 516 foreach ( $taxonomies as $_tax ) { 517 $term_hierarchy = _get_term_hierarchy( $_tax ); 518 $exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions ); 519 } 520 } 521 522 if ( ! empty( $exclusions ) ) { 523 $exclusions = 't.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')'; 524 } else { 525 $exclusions = ''; 526 } 527 528 /** 529 * Filters the terms to exclude from the terms query. 530 * 531 * @since 2.3.0 532 * 533 * @param string $exclusions `NOT IN` clause of the terms query. 534 * @param array $args An array of terms query arguments. 535 * @param string[] $taxonomies An array of taxonomy names. 536 */ 537 $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies ); 538 539 if ( ! empty( $exclusions ) ) { 540 // Strip leading 'AND'. Must do string manipulation here for backward compatibility with filter. 541 $this->sql_clauses['where']['exclusions'] = preg_replace( '/^\s*AND\s*/', '', $exclusions ); 542 } 543 544 if ( '' === $args['name'] ) { 545 $args['name'] = array(); 546 } else { 547 $args['name'] = (array) $args['name']; 548 } 549 550 if ( ! empty( $args['name'] ) ) { 551 $names = $args['name']; 552 553 foreach ( $names as &$_name ) { 554 // `sanitize_term_field()` returns slashed data. 555 $_name = stripslashes( sanitize_term_field( 'name', $_name, 0, reset( $taxonomies ), 'db' ) ); 556 } 557 558 $this->sql_clauses['where']['name'] = "t.name IN ('" . implode( "', '", array_map( 'esc_sql', $names ) ) . "')"; 559 } 560 561 if ( '' === $args['slug'] ) { 562 $args['slug'] = array(); 563 } else { 564 $args['slug'] = array_map( 'sanitize_title', (array) $args['slug'] ); 565 } 566 567 if ( ! empty( $args['slug'] ) ) { 568 $slug = implode( "', '", $args['slug'] ); 569 570 $this->sql_clauses['where']['slug'] = "t.slug IN ('" . $slug . "')"; 571 } 572 573 if ( '' === $args['term_taxonomy_id'] ) { 574 $args['term_taxonomy_id'] = array(); 575 } else { 576 $args['term_taxonomy_id'] = array_map( 'intval', (array) $args['term_taxonomy_id'] ); 577 } 578 579 if ( ! empty( $args['term_taxonomy_id'] ) ) { 580 $tt_ids = implode( ',', $args['term_taxonomy_id'] ); 581 582 $this->sql_clauses['where']['term_taxonomy_id'] = "tt.term_taxonomy_id IN ({$tt_ids})"; 583 } 584 585 if ( ! empty( $args['name__like'] ) ) { 586 $this->sql_clauses['where']['name__like'] = $wpdb->prepare( 587 't.name LIKE %s', 588 '%' . $wpdb->esc_like( $args['name__like'] ) . '%' 589 ); 590 } 591 592 if ( ! empty( $args['description__like'] ) ) { 593 $this->sql_clauses['where']['description__like'] = $wpdb->prepare( 594 'tt.description LIKE %s', 595 '%' . $wpdb->esc_like( $args['description__like'] ) . '%' 596 ); 597 } 598 599 if ( '' === $args['object_ids'] ) { 600 $args['object_ids'] = array(); 601 } else { 602 $args['object_ids'] = array_map( 'intval', (array) $args['object_ids'] ); 603 } 604 605 if ( ! empty( $args['object_ids'] ) ) { 606 $object_ids = implode( ', ', $args['object_ids'] ); 607 608 $this->sql_clauses['where']['object_ids'] = "tr.object_id IN ($object_ids)"; 609 } 610 611 /* 612 * When querying for object relationships, the 'count > 0' check 613 * added by 'hide_empty' is superfluous. 614 */ 615 if ( ! empty( $args['object_ids'] ) ) { 616 $args['hide_empty'] = false; 617 } 618 619 if ( '' !== $parent ) { 620 $parent = (int) $parent; 621 $this->sql_clauses['where']['parent'] = "tt.parent = '$parent'"; 622 } 623 624 $hierarchical = $args['hierarchical']; 625 if ( 'count' === $args['fields'] ) { 626 $hierarchical = false; 627 } 628 if ( $args['hide_empty'] && ! $hierarchical ) { 629 $this->sql_clauses['where']['count'] = 'tt.count > 0'; 630 } 631 632 $number = $args['number']; 633 $offset = $args['offset']; 634 635 // Don't limit the query results when we have to descend the family tree. 636 if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) { 637 if ( $offset ) { 638 $limits = 'LIMIT ' . $offset . ',' . $number; 639 } else { 640 $limits = 'LIMIT ' . $number; 641 } 642 } else { 643 $limits = ''; 644 } 645 646 if ( ! empty( $args['search'] ) ) { 647 $this->sql_clauses['where']['search'] = $this->get_search_sql( $args['search'] ); 648 } 649 650 // Meta query support. 651 $join = ''; 652 $distinct = ''; 653 654 // Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback. 655 $this->meta_query->parse_query_vars( $this->query_vars ); 656 $mq_sql = $this->meta_query->get_sql( 'term', 't', 'term_id' ); 657 $meta_clauses = $this->meta_query->get_clauses(); 658 659 if ( ! empty( $meta_clauses ) ) { 660 $join .= $mq_sql['join']; 661 662 // Strip leading 'AND'. 663 $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $mq_sql['where'] ); 664 665 $distinct .= 'DISTINCT'; 666 667 } 668 669 $selects = array(); 670 switch ( $args['fields'] ) { 671 case 'count': 672 $orderby = ''; 673 $order = ''; 674 $selects = array( 'COUNT(*)' ); 675 break; 676 default: 677 $selects = array( 't.term_id' ); 678 if ( 'all_with_object_id' === $args['fields'] && ! empty( $args['object_ids'] ) ) { 679 $selects[] = 'tr.object_id'; 680 } 681 break; 682 } 683 684 $_fields = $args['fields']; 685 686 /** 687 * Filters the fields to select in the terms query. 688 * 689 * Field lists modified using this filter will only modify the term fields returned 690 * by the function when the `$fields` parameter set to 'count' or 'all'. In all other 691 * cases, the term fields in the results array will be determined by the `$fields` 692 * parameter alone. 693 * 694 * Use of this filter can result in unpredictable behavior, and is not recommended. 695 * 696 * @since 2.8.0 697 * 698 * @param string[] $selects An array of fields to select for the terms query. 699 * @param array $args An array of term query arguments. 700 * @param string[] $taxonomies An array of taxonomy names. 701 */ 702 $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) ); 703 704 $join .= " INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id"; 705 706 if ( ! empty( $this->query_vars['object_ids'] ) ) { 707 $join .= " INNER JOIN {$wpdb->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id"; 708 $distinct = 'DISTINCT'; 709 } 710 711 $where = implode( ' AND ', $this->sql_clauses['where'] ); 712 713 $pieces = array( 'fields', 'join', 'where', 'distinct', 'orderby', 'order', 'limits' ); 714 715 /** 716 * Filters the terms query SQL clauses. 717 * 718 * @since 3.1.0 719 * 720 * @param string[] $clauses { 721 * Associative array of the clauses for the query. 722 * 723 * @type string $fields The SELECT clause of the query. 724 * @type string $join The JOIN clause of the query. 725 * @type string $where The WHERE clause of the query. 726 * @type string $distinct The DISTINCT clause of the query. 727 * @type string $orderby The ORDER BY clause of the query. 728 * @type string $order The ORDER clause of the query. 729 * @type string $limits The LIMIT clause of the query. 730 * } 731 * @param string[] $taxonomies An array of taxonomy names. 732 * @param array $args An array of term query arguments. 733 */ 734 $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args ); 735 736 $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : ''; 737 $join = isset( $clauses['join'] ) ? $clauses['join'] : ''; 738 $where = isset( $clauses['where'] ) ? $clauses['where'] : ''; 739 $distinct = isset( $clauses['distinct'] ) ? $clauses['distinct'] : ''; 740 $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : ''; 741 $order = isset( $clauses['order'] ) ? $clauses['order'] : ''; 742 $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : ''; 743 744 $fields_is_filtered = implode( ', ', $selects ) !== $fields; 745 746 if ( $where ) { 747 $where = "WHERE $where"; 748 } 749 750 $this->sql_clauses['select'] = "SELECT $distinct $fields"; 751 $this->sql_clauses['from'] = "FROM $wpdb->terms AS t $join"; 752 $this->sql_clauses['orderby'] = $orderby ? "$orderby $order" : ''; 753 $this->sql_clauses['limits'] = $limits; 754 755 // Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841. 756 $this->request = 757 "{$this->sql_clauses['select']} 758 {$this->sql_clauses['from']} 759 {$where} 760 {$this->sql_clauses['orderby']} 761 {$this->sql_clauses['limits']}"; 762 763 $this->terms = null; 764 765 /** 766 * Filters the terms array before the query takes place. 767 * 768 * Return a non-null value to bypass WordPress' default term queries. 769 * 770 * @since 5.3.0 771 * 772 * @param array|null $terms Return an array of term data to short-circuit WP's term query, 773 * or null to allow WP queries to run normally. 774 * @param WP_Term_Query $query The WP_Term_Query instance, passed by reference. 775 */ 776 $this->terms = apply_filters_ref_array( 'terms_pre_query', array( $this->terms, &$this ) ); 777 778 if ( null !== $this->terms ) { 779 return $this->terms; 780 } 781 782 if ( $args['cache_results'] ) { 783 $cache_key = $this->generate_cache_key( $args, $this->request ); 784 $cache = wp_cache_get( $cache_key, 'term-queries' ); 785 786 if ( false !== $cache ) { 787 if ( 'ids' === $_fields ) { 788 $cache = array_map( 'intval', $cache ); 789 } elseif ( 'count' !== $_fields ) { 790 if ( ( 'all_with_object_id' === $_fields && ! empty( $args['object_ids'] ) ) 791 || ( 'all' === $_fields && $args['pad_counts'] || $fields_is_filtered ) 792 ) { 793 $term_ids = wp_list_pluck( $cache, 'term_id' ); 794 } else { 795 $term_ids = array_map( 'intval', $cache ); 796 } 797 798 _prime_term_caches( $term_ids, $args['update_term_meta_cache'] ); 799 800 $term_objects = $this->populate_terms( $cache ); 801 $cache = $this->format_terms( $term_objects, $_fields ); 802 } 803 804 $this->terms = $cache; 805 return $this->terms; 806 } 807 } 808 809 if ( 'count' === $_fields ) { 810 $count = $wpdb->get_var( $this->request ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 811 if ( $args['cache_results'] ) { 812 wp_cache_set( $cache_key, $count, 'term-queries' ); 813 } 814 return $count; 815 } 816 817 $terms = $wpdb->get_results( $this->request ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 818 819 if ( empty( $terms ) ) { 820 if ( $args['cache_results'] ) { 821 wp_cache_add( $cache_key, array(), 'term-queries' ); 822 } 823 return array(); 824 } 825 826 $term_ids = wp_list_pluck( $terms, 'term_id' ); 827 _prime_term_caches( $term_ids, false ); 828 $term_objects = $this->populate_terms( $terms ); 829 830 if ( $child_of ) { 831 foreach ( $taxonomies as $_tax ) { 832 $children = _get_term_hierarchy( $_tax ); 833 if ( ! empty( $children ) ) { 834 $term_objects = _get_term_children( $child_of, $term_objects, $_tax ); 835 } 836 } 837 } 838 839 // Update term counts to include children. 840 if ( $args['pad_counts'] && 'all' === $_fields ) { 841 foreach ( $taxonomies as $_tax ) { 842 _pad_term_counts( $term_objects, $_tax ); 843 } 844 } 845 846 // Make sure we show empty categories that have children. 847 if ( $hierarchical && $args['hide_empty'] && is_array( $term_objects ) ) { 848 foreach ( $term_objects as $k => $term ) { 849 if ( ! $term->count ) { 850 $children = get_term_children( $term->term_id, $term->taxonomy ); 851 852 if ( is_array( $children ) ) { 853 foreach ( $children as $child_id ) { 854 $child = get_term( $child_id, $term->taxonomy ); 855 if ( $child->count ) { 856 continue 2; 857 } 858 } 859 } 860 861 // It really is empty. 862 unset( $term_objects[ $k ] ); 863 } 864 } 865 } 866 867 // Hierarchical queries are not limited, so 'offset' and 'number' must be handled now. 868 if ( $hierarchical && $number && is_array( $term_objects ) ) { 869 if ( $offset >= count( $term_objects ) ) { 870 $term_objects = array(); 871 } else { 872 $term_objects = array_slice( $term_objects, $offset, $number, true ); 873 } 874 } 875 876 // Prime termmeta cache. 877 if ( $args['update_term_meta_cache'] ) { 878 $term_ids = wp_list_pluck( $term_objects, 'term_id' ); 879 wp_lazyload_term_meta( $term_ids ); 880 } 881 882 if ( 'all_with_object_id' === $_fields && ! empty( $args['object_ids'] ) ) { 883 $term_cache = array(); 884 foreach ( $term_objects as $term ) { 885 $object = new stdClass(); 886 $object->term_id = $term->term_id; 887 $object->object_id = $term->object_id; 888 $term_cache[] = $object; 889 } 890 } elseif ( 'all' === $_fields && $args['pad_counts'] ) { 891 $term_cache = array(); 892 foreach ( $term_objects as $term ) { 893 $object = new stdClass(); 894 $object->term_id = $term->term_id; 895 $object->count = $term->count; 896 $term_cache[] = $object; 897 } 898 } elseif ( $fields_is_filtered ) { 899 $term_cache = $term_objects; 900 } else { 901 $term_cache = wp_list_pluck( $term_objects, 'term_id' ); 902 } 903 904 if ( $args['cache_results'] ) { 905 wp_cache_add( $cache_key, $term_cache, 'term-queries' ); 906 } 907 908 $this->terms = $this->format_terms( $term_objects, $_fields ); 909 910 return $this->terms; 911 } 912 913 /** 914 * Parse and sanitize 'orderby' keys passed to the term query. 915 * 916 * @since 4.6.0 917 * 918 * @param string $orderby_raw Alias for the field to order by. 919 * @return string|false Value to used in the ORDER clause. False otherwise. 920 */ 921 protected function parse_orderby( $orderby_raw ) { 922 $_orderby = strtolower( $orderby_raw ); 923 $maybe_orderby_meta = false; 924 925 if ( in_array( $_orderby, array( 'term_id', 'name', 'slug', 'term_group' ), true ) ) { 926 $orderby = "t.$_orderby"; 927 } elseif ( in_array( $_orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id', 'description' ), true ) ) { 928 $orderby = "tt.$_orderby"; 929 } elseif ( 'term_order' === $_orderby ) { 930 $orderby = 'tr.term_order'; 931 } elseif ( 'include' === $_orderby && ! empty( $this->query_vars['include'] ) ) { 932 $include = implode( ',', wp_parse_id_list( $this->query_vars['include'] ) ); 933 $orderby = "FIELD( t.term_id, $include )"; 934 } elseif ( 'slug__in' === $_orderby && ! empty( $this->query_vars['slug'] ) && is_array( $this->query_vars['slug'] ) ) { 935 $slugs = implode( "', '", array_map( 'sanitize_title_for_query', $this->query_vars['slug'] ) ); 936 $orderby = "FIELD( t.slug, '" . $slugs . "')"; 937 } elseif ( 'none' === $_orderby ) { 938 $orderby = ''; 939 } elseif ( empty( $_orderby ) || 'id' === $_orderby || 'term_id' === $_orderby ) { 940 $orderby = 't.term_id'; 941 } else { 942 $orderby = 't.name'; 943 944 // This may be a value of orderby related to meta. 945 $maybe_orderby_meta = true; 946 } 947 948 /** 949 * Filters the ORDERBY clause of the terms query. 950 * 951 * @since 2.8.0 952 * 953 * @param string $orderby `ORDERBY` clause of the terms query. 954 * @param array $args An array of term query arguments. 955 * @param string[] $taxonomies An array of taxonomy names. 956 */ 957 $orderby = apply_filters( 'get_terms_orderby', $orderby, $this->query_vars, $this->query_vars['taxonomy'] ); 958 959 // Run after the 'get_terms_orderby' filter for backward compatibility. 960 if ( $maybe_orderby_meta ) { 961 $maybe_orderby_meta = $this->parse_orderby_meta( $_orderby ); 962 if ( $maybe_orderby_meta ) { 963 $orderby = $maybe_orderby_meta; 964 } 965 } 966 967 return $orderby; 968 } 969 970 /** 971 * Format response depending on field requested. 972 * 973 * @since 6.0.0 974 * 975 * @param WP_Term[] $term_objects Array of term objects. 976 * @param string $_fields Field to format. 977 * 978 * @return WP_Term[]|int[]|string[] Array of terms / strings / ints depending on field requested. 979 */ 980 protected function format_terms( $term_objects, $_fields ) { 981 $_terms = array(); 982 if ( 'id=>parent' === $_fields ) { 983 foreach ( $term_objects as $term ) { 984 $_terms[ $term->term_id ] = $term->parent; 985 } 986 } elseif ( 'ids' === $_fields ) { 987 foreach ( $term_objects as $term ) { 988 $_terms[] = (int) $term->term_id; 989 } 990 } elseif ( 'tt_ids' === $_fields ) { 991 foreach ( $term_objects as $term ) { 992 $_terms[] = (int) $term->term_taxonomy_id; 993 } 994 } elseif ( 'names' === $_fields ) { 995 foreach ( $term_objects as $term ) { 996 $_terms[] = $term->name; 997 } 998 } elseif ( 'slugs' === $_fields ) { 999 foreach ( $term_objects as $term ) { 1000 $_terms[] = $term->slug; 1001 } 1002 } elseif ( 'id=>name' === $_fields ) { 1003 foreach ( $term_objects as $term ) { 1004 $_terms[ $term->term_id ] = $term->name; 1005 } 1006 } elseif ( 'id=>slug' === $_fields ) { 1007 foreach ( $term_objects as $term ) { 1008 $_terms[ $term->term_id ] = $term->slug; 1009 } 1010 } elseif ( 'all' === $_fields || 'all_with_object_id' === $_fields ) { 1011 $_terms = $term_objects; 1012 } 1013 1014 return $_terms; 1015 } 1016 1017 /** 1018 * Generate the ORDER BY clause for an 'orderby' param that is potentially related to a meta query. 1019 * 1020 * @since 4.6.0 1021 * 1022 * @param string $orderby_raw Raw 'orderby' value passed to WP_Term_Query. 1023 * @return string ORDER BY clause. 1024 */ 1025 protected function parse_orderby_meta( $orderby_raw ) { 1026 $orderby = ''; 1027 1028 // Tell the meta query to generate its SQL, so we have access to table aliases. 1029 $this->meta_query->get_sql( 'term', 't', 'term_id' ); 1030 $meta_clauses = $this->meta_query->get_clauses(); 1031 if ( ! $meta_clauses || ! $orderby_raw ) { 1032 return $orderby; 1033 } 1034 1035 $allowed_keys = array(); 1036 $primary_meta_key = null; 1037 $primary_meta_query = reset( $meta_clauses ); 1038 if ( ! empty( $primary_meta_query['key'] ) ) { 1039 $primary_meta_key = $primary_meta_query['key']; 1040 $allowed_keys[] = $primary_meta_key; 1041 } 1042 $allowed_keys[] = 'meta_value'; 1043 $allowed_keys[] = 'meta_value_num'; 1044 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) ); 1045 1046 if ( ! in_array( $orderby_raw, $allowed_keys, true ) ) { 1047 return $orderby; 1048 } 1049 1050 switch ( $orderby_raw ) { 1051 case $primary_meta_key: 1052 case 'meta_value': 1053 if ( ! empty( $primary_meta_query['type'] ) ) { 1054 $orderby = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})"; 1055 } else { 1056 $orderby = "{$primary_meta_query['alias']}.meta_value"; 1057 } 1058 break; 1059 1060 case 'meta_value_num': 1061 $orderby = "{$primary_meta_query['alias']}.meta_value+0"; 1062 break; 1063 1064 default: 1065 if ( array_key_exists( $orderby_raw, $meta_clauses ) ) { 1066 // $orderby corresponds to a meta_query clause. 1067 $meta_clause = $meta_clauses[ $orderby_raw ]; 1068 $orderby = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})"; 1069 } 1070 break; 1071 } 1072 1073 return $orderby; 1074 } 1075 1076 /** 1077 * Parse an 'order' query variable and cast it to ASC or DESC as necessary. 1078 * 1079 * @since 4.6.0 1080 * 1081 * @param string $order The 'order' query variable. 1082 * @return string The sanitized 'order' query variable. 1083 */ 1084 protected function parse_order( $order ) { 1085 if ( ! is_string( $order ) || empty( $order ) ) { 1086 return 'DESC'; 1087 } 1088 1089 if ( 'ASC' === strtoupper( $order ) ) { 1090 return 'ASC'; 1091 } else { 1092 return 'DESC'; 1093 } 1094 } 1095 1096 /** 1097 * Used internally to generate a SQL string related to the 'search' parameter. 1098 * 1099 * @since 4.6.0 1100 * 1101 * @global wpdb $wpdb WordPress database abstraction object. 1102 * 1103 * @param string $search Search string. 1104 * @return string Search SQL. 1105 */ 1106 protected function get_search_sql( $search ) { 1107 global $wpdb; 1108 1109 $like = '%' . $wpdb->esc_like( $search ) . '%'; 1110 1111 return $wpdb->prepare( '((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like ); 1112 } 1113 1114 /** 1115 * Creates an array of term objects from an array of term IDs. 1116 * 1117 * Also discards invalid term objects. 1118 * 1119 * @since 4.9.8 1120 * 1121 * @param Object[]|int[] $terms List of objects or term ids. 1122 * @return WP_Term[] Array of `WP_Term` objects. 1123 */ 1124 protected function populate_terms( $terms ) { 1125 $term_objects = array(); 1126 if ( ! is_array( $terms ) ) { 1127 return $term_objects; 1128 } 1129 1130 foreach ( $terms as $key => $term_data ) { 1131 if ( is_object( $term_data ) && property_exists( $term_data, 'term_id' ) ) { 1132 $term = get_term( $term_data->term_id ); 1133 if ( property_exists( $term_data, 'object_id' ) ) { 1134 $term->object_id = (int) $term_data->object_id; 1135 } 1136 if ( property_exists( $term_data, 'count' ) ) { 1137 $term->count = (int) $term_data->count; 1138 } 1139 } else { 1140 $term = get_term( $term_data ); 1141 } 1142 1143 if ( $term instanceof WP_Term ) { 1144 $term_objects[ $key ] = $term; 1145 } 1146 } 1147 1148 return $term_objects; 1149 } 1150 1151 /** 1152 * Generate cache key. 1153 * 1154 * @since 6.2.0 1155 * 1156 * @global wpdb $wpdb WordPress database abstraction object. 1157 * 1158 * @param array $args WP_Term_Query arguments. 1159 * @param string $sql SQL statement. 1160 * 1161 * @return string Cache key. 1162 */ 1163 protected function generate_cache_key( array $args, $sql ) { 1164 global $wpdb; 1165 // $args can be anything. Only use the args defined in defaults to compute the key. 1166 $cache_args = wp_array_slice_assoc( $args, array_keys( $this->query_var_defaults ) ); 1167 1168 unset( $cache_args['cache_results'], $cache_args['update_term_meta_cache'] ); 1169 1170 if ( 'count' !== $args['fields'] && 'all_with_object_id' !== $args['fields'] ) { 1171 $cache_args['fields'] = 'all'; 1172 } 1173 $taxonomies = (array) $args['taxonomy']; 1174 1175 // Replace wpdb placeholder in the SQL statement used by the cache key. 1176 $sql = $wpdb->remove_placeholder_escape( $sql ); 1177 1178 $key = md5( serialize( $cache_args ) . serialize( $taxonomies ) . $sql ); 1179 $last_changed = wp_cache_get_last_changed( 'terms' ); 1180 return "get_terms:$key:$last_changed"; 1181 } 1182 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Sun Apr 28 08:20:02 2024 | Cross-referenced by PHPXref |