[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-term-query.php (source)

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


Generated : Thu Nov 6 08:20:07 2025 Cross-referenced by PHPXref