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


Generated : Tue Sep 8 08:20:28 2026 Cross-referenced by PHPXref