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