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